Next.js Discord

Discord Forum

Session management using JWT and XSS protection

Unanswered
Giant panda posted this in #help-forum
Open in Discord
Giant pandaOP
Hey folks! I've been doing some research about auth (session) flow using JWT during last few days and found myself being lost among the plenty recommendations, warns, restrictions and best practices.

So basically what I have is the following setup:
- classical REST API which serves JWT pair on login (access & refresh)
- client app built with next js and with using next auth
So far, while being in closed alpha, I was okay just storing JWT in local storage, but obviously it's very much vulnerable for XSS attacks. So I've started to investigate other possible approaches. While being protected from the SCRF, I found that XSS is much more dangerous and normally it's much more easier to protect the system from the CSRF rather then XSS.

I've started to sniff around about storing JWT in http-only coockie. Which is kind of weird, since traditional session-id approach is much more straingforward and simply appropriate (but my backend cannot provide it). Anyway, I found a few well-writen articles which describes such strategy. For example here https://blog.logrocket.com/jwt-authentication-best-practices/ the guys describes the following approach:
A JWT needs to be stored in a safe place inside the user’s browser. Storing sensitive data inside localStorage is a bad idea. If any of the third-party scripts you include in your page are compromised, it can access all your users’ tokens.
You should always store JWTs inside an HttpOnly cookie. This is a special kind of cookie that’s only sent in HTTP requests to the server.


Which sounds okay, but I got a few questions so far:
- how to provide smooth (from the client side UX perspective) behaviour for the token refresh
- speaking about storing JWT. For example chat GPT set's JWT as auth header, but I do really wander how they store it, if it's not a local/session storage.

I would more then grateful for the any tips for my case and generally a critics about any of my conclusion above.

2 Replies

Giant pandaOP
bump
i have no comments on the main questions, but in react applications, xss protection is built in. your entire application is xss-safe, except places where you (or a library you use) use dangerouslySetInnerHTML. if you do use dangerouslySetInnerHTML, you simply need to sanitise whatever content passed to dangerouslySetInnerHTML using the zillion xss sanitiser packages on npm