最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - Does a server push need to be secured with JWT? What’s the best practice for a notification system? - Stack Overflo

programmeradmin4浏览0评论

I’m working on my first website, using Fastify, and my goal today is to securely implement friend invitations using JWT. The issue I’m encountering is that my server needs to notify the client that it has received an invitation. To address this, I’ve found three possible options:

  1. Fetch the server every 5 seconds to check if I’ve received an invitation. I think this is a terrible option.

  2. Another option is to use WebSockets to communicate the invitation, but I can’t send the JWT for authentication (as explained in this post, i can, but it’s mentioned that there is a better solution).

  3. Use server-sent-event. I'm on this method actually, i can send the jwt inside a get request like this :

async function sseConnection(token: string) {
    const res = await fetch("http://localhost:3000/user-management/sse", {
        method: 'GET',
        headers: {
            'Content-Type': 'text/event-stream',
            'Authorization': `Bearer ${token}`
        }
    })

    const reader = res.body?.pipeThrough(new TextDecoderStream()).getReader() ?? null;
    while (reader) {
        const {value, done} = await reader.read();
        if (done) break;
        const parse = sseParse(value);
        sseHandler(parse.event, parse.data);
    }
}

I found a Fastify plugin for SSE: fastify-sse-v2. Each time I use the .sse method of my response, it triggers reader.read(), and I receive my data.

I need to handle a lot of edge cases, and my code is starting to get messy. I could continue in this direction, but I wanted to ask here if it's necessary to secure this connection with JWT.

If I don't protect it with JWT, I can use EventSource in the browser, and it automatically parses the data. Im open to your suggestions.

发布评论

评论列表(0)

  1. 暂无评论