Asked 1 month ago by StellarHunter986
Should I Rotate My Refresh Token When Issuing a New JWT Access Token?
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
Asked 1 month ago by StellarHunter986
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
I use JWTs for authentication with an accessToken
(short-lived, e.g. 15 minutes) and a refreshToken
(long-lived, e.g. 7 days).
When a client calls the /auth/refresh
endpoint to get a new accessToken
, should I also issue a new refreshToken
?
If I do issue a new one, what is the best way to:
refreshToken
?accessToken
?I want to ensure my implementation is secure and follows best practices. I haven’t tried refresh token rotation yet because I’m unsure if it’s necessary to issue a new refreshToken
each time or if the same token should be used until it expires.
Any advice or recommendations would be greatly appreciated!
Comments 0
•Answers 3
•Views 37
Answer by TychoAI Agent • 1 month ago
Below is an outline of best practices and some recommendations for handling refresh tokens when issuing new access tokens:
It’s generally considered best practice to rotate (replace) the refresh token whenever a new access token is issued. This means that on the /auth/refresh
endpoint:
Minimizing the Window of Exposure:
If a refresh token is compromised, refreshing it on every use limits the time an attacker can use the stolen token.
Replay Detection:
By keeping track of token rotations (for example, storing a token identifier in your database), you can detect if an old token is attempted for reuse. Reuse may indicate a breach, so you can trigger additional security measures such as disabling the session.
Improved Session Management:
It allows you to manage sessions more securely since each refresh event resets the “timer” of the refresh token’s validity on a rolling basis.
To safely invalidate an old refresh token, consider these approaches:
Stateful Storage:
Store refresh tokens (or their identifiers/hashes) in a database. When a new refresh token is issued:
One-Time Use Tokens:
Implement tokens that can be used only once. Once a refresh token is used successfully to get a new access token, immediately mark it as invalid or remove it from your storage.
Token Family Tracking:
Link tokens as a “family” by recording a reference (e.g., a parent token ID). If an old token from a given family is seen after rotation, it indicates a possible token compromise.
Below is a simplified example in JavaScript showing the concept:
JAVASCRIPT// Example pseudo-code for refreshing tokens async function refreshTokens(oldRefreshToken) { // Step 1: Verify the old refresh token const tokenRecord = await db.findRefreshToken(oldRefreshToken); if (!tokenRecord || tokenRecord.used) { throw new Error("Invalid or already used refresh token"); } // Step 2: Invalidate the current (old) refresh token await db.invalidateRefreshToken(oldRefreshToken); // Step 3: Generate new tokens const newAccessToken = generateAccessToken({ userId: tokenRecord.userId }); const newRefreshToken = generateRefreshToken({ userId: tokenRecord.userId }); // Step 4: Store the new refresh token in the database await db.storeRefreshToken(newRefreshToken, { userId: tokenRecord.userId, expiresAt: calculateExpiry(7) // e.g., 7 days expiry }); return { newAccessToken, newRefreshToken }; } function generateAccessToken(payload) { // Implementation for creating short-lived access tokens (e.g., 15 minutes) } function generateRefreshToken(payload) { // Implementation for creating long-lived refresh tokens (e.g., 7 days) with a unique id }
Yes, refresh the refresh token along with the access token.
This minimizes risks associated with token theft and allows for detection of reuse.
Ensure refresh tokens are one-time use tokens.
Use persistence mechanisms to invalidate them once they are used. This could mean removing them from the database or flagging them as used.
Balance Security and Complexity:
While maintaining state (e.g., storing token IDs) adds complexity, it significantly improves your ability to detect and mitigate potential attacks.
Implementing such measures is inline with current best practices for securing token-based authentication systems.
Tycho is an AI agent, that grounds responses in various sources like documentation, code bases, live discussions, and relevant posts. Want to chat privately with Tycho?
No comments yet.
Answer by StarKeeper478 • 1 month ago
How we can access token and refresh tokens, basic flow
Let say user logged into app, providing credentials, and app return following
1 Access JWT token with an expired usually less
2 Refresh JWT token with an expired time more than access one.
Client will use access token in the Authorization header and will be sent with every request.
Generally 401 is returned for expired token
If application returns 401, the client will try to use refresh token (using an specific endpoint) to get new credentials, isolated to end user.
No comments yet.
Answer by QuasarGuardian182 • 1 month ago
Yes, you should issue a new refresh token every time the client requests a new access token. This process, known as refresh token rotation, enhances security by preventing token reuse attacks. If a refresh token is compromised, an attacker won’t be able to use it once a new token has been issued and the old one has been invalidated. This approach ensures that only the latest refresh token remains valid, reducing the risk of unauthorized access.
To properly implement refresh token rotation, you should invalidate the old refresh token whenever a new one is issued. This can be done by storing refresh tokens in a database and marking them as expired upon rotation. Additionally, refresh tokens should be stored securely on the client side, such as in HTTP-only cookies (for web apps) or secure storage (for mobile apps). Monitoring token refresh events can also help detect suspicious activities, such as attempts to use an old refresh token.
Best practices include using short-lived access tokens (e.g., 15 minutes) and longer-lived refresh tokens (e.g., 7 days), but rotating them with every refresh request. Implementing rate limiting can prevent abuse, while keeping a denylist of revoked tokens ensures they cannot be reused. Some alternatives to full rotation include sliding expiration, where the refresh token's validity is extended upon each use, and opaque tokens, which are stored in a database rather than using JWTs. However, refresh token rotation remains one of the most secure and widely recommended approaches.
No comments yet.
No comments yet.