hantoren
hantoren

Reputation: 1235

Best way to store tokens in Next.js for authentication

I am working on a Next.js application and implementing authentication using tokens. I have three tokens: accessToken, refreshToken (both are jwt and contain userId, email and role), and csrfToken (cryptographically random 32 digit character string). I would like to know the best practices for storing these tokens securely in my Next.js application. Here is my current approach, and I would appreciate feedback and suggestions on whether this is the recommended way or if there are better alternatives.

My suggestion is to store the refreshToken in a secure, HTTP-only cookie. This approach ensures that the token is protected from cross-site scripting (XSS) attacks and cannot be accessed by JavaScript.

As for the accessToken and csrfToken, I plan to receive them as a response from the login POST request and then store them in Next.js using a context provider. By doing this, I can easily access these tokens across different components and pages within my application.

Is this approach recommended? Are there any potential security risks or drawbacks that I should be aware of? Are there any alternative methods that are considered best practices for storing tokens in a Next.js application? Any insights or examples would be greatly appreciated.

Upvotes: 2

Views: 4668

Answers (1)

Gary Archer
Gary Archer

Reputation: 29243

The OAuth for Browser Based Apps article provides some up to date best practices. Secure values cannot be stored entirely safely in the browser. Section 6.2 describes a backend for frontend approach that is commonly used these days.

Extra attack vectors around XSS concerns and token interception mean that HTTP-only cookie based security is perceived to be safer, and threats better understood, when data requests are sent.

A solid approach is to store all OAuth tokens in the latest HTTP-only SameSite=strict cookies. The CSRF token is a secondary value which can be stored in memory or even local storage. If it is exfiltrated from the browser it does not provide access to secured data.

With cookies, XSS remains a concern. For any browser based app with XSS vulnerabilities, malicious code can do anything your app can do, eg send the cookie to the backend. Therefore also follow OWASP XSS best practices, including a Content Security Policy, which can help to mitigate data exfiltration risks.

Upvotes: 1

Related Questions