I'm working on a web app using Next.js for the frontend, Spring Boot for the backend, MongoDB, and Supabase. I've already implemented access tokens, which I'm storing in HTTP-only cookies, but they expire after 1 hour, which means users often have to log in again. I understand that refresh tokens can help with this, but I'm not sure about the best way to store them securely. Should I also store refresh tokens in cookies, or is it better to use local storage since my access tokens are already in cookies? What would the ideal flow for managing refresh tokens look like in my stack? Thanks for any guidance!
6 Answers
I suggest keeping refresh tokens on your server. Access tokens should be short-lived, and the correlation with refresh tokens should be managed server-side to avoid users refreshing their own sessions. Make sure to delete both tokens when a user logs out to keep things secure.
I think storing refresh tokens in cookies is the way to go! I’m currently figuring this out myself, so I’ll keep an eye on this thread for more insights.
It's generally best to store refresh tokens in HTTP-only cookies. Local storage can be vulnerable to XSS attacks, so keeping refresh tokens in cookies adds a layer of security. Also, make sure to set appropriate expiry dates for both tokens to manage user sessions effectively.
True, but if you have an XSS issue, an attacker could still access your cookies, right?
Definitely go with HTTP-only cookies for refresh tokens too. It's easier to manage token expiration this way, plus it keeps users logged in without the hassle of frequent relogins.
I recommend keeping refresh tokens in your database and only accessing them through the backend. For example, store access tokens in cookies that expire quickly (like 15 minutes), while refresh tokens can last longer (like 15 days). When a user logs out, invalidate both tokens to ensure they’re required to log in again.
How do you ensure the user gets a new access token without logging in again?
If the access token expires, what happens to the session until the user refreshes?
Here’s a possible flow: After a user logs in, the server issues both access and refresh tokens. The access token is stored in an HTTP-only cookie and used for requests. When the access token expires, make an API call to a `/refresh` endpoint using the refresh token in the cookie to get new tokens. If you successfully refresh, you can replay the original request using the new access token. If the refresh fails, the user needs to log back in.
How does the server authenticate the user when the access token is expired? Do they just use the refresh token?