Understanding JWT Expiration Time claim (exp)
JSON Web Tokens (JWT) 的过期时间通过 `exp` 声明指定令牌失效时间。设置合理的过期时间需权衡安全性和用户体验:短时间提高安全性但频繁刷新;长时间则增加风险。常用短时(5-15分钟)、中时(1-24小时)和长时(7-30天)令牌。结合刷新令牌可提升便利性,并遵循最佳实践如使用短时访问令牌、安全存储刷新令牌及处理过期情况以增强安全性。 2025-9-13 11:27:55 Author: securityboulevard.com(查看原文) 阅读量:2 收藏

JSON Web Tokens (JWT) are a popular mechanism for authentication and authorization in modern web applications. One critical aspect of JWT security and usability is its expiration time. Understanding how JWT expiration works, the best practices around it, and potential security concerns is essential for developers and security professionals.

What is JWT Expiration Time?

JWT expiration time is a claim (exp) within the token that specifies the exact timestamp when the token becomes invalid. This timestamp is expressed in Unix time (seconds since January 1, 1970). A sample JWT payload with an expiration time looks like this:

{ "sub": "1234567890", "name": "John Doe", "iat": 1717023000, "exp": 1717026600 } 
  • iat (Issued At) – Timestamp when the token was issued.
  • exp (Expiration Time) – Timestamp when the token expires.

Setting JWT Expiration Time

JWT expiration time is usually set at the time of token creation. For example, in Node.js using jsonwebtoken:

Techstrong Gang Youtube

const jwt = require('jsonwebtoken'); const token = jwt.sign( { userId: 1 }, 'your_secret_key', { expiresIn: '1h' } // Token expires in 1 hour ); console.log(token); 

This means the token will expire exactly one hour after issuance.

Considerations When Setting Expiration Time

  1. Security vs. Usability Tradeoff:
    • Short expiration times improve security by reducing the window in which a stolen token can be used.
    • Long expiration times reduce the frequency of token refreshes but increase security risks.
  2. Stateless vs. Stateful Authentication:
    • Stateless authentication (JWT without a backend session store) requires careful expiration handling.
    • Stateful authentication (JWT stored and tracked in a database) allows manual invalidation.
  3. Use Cases:
    • Short-lived Tokens (5–15 minutes): Suitable for high-security applications like banking.
    • Medium-lived Tokens (1–24 hours): Used in general web applications.
    • Long-lived Tokens (7–30 days): Used for refresh tokens or low-risk scenarios.

Refresh Tokens and Expiration Handling

Since short-lived JWTs can be inconvenient for users, refresh tokens are used to obtain new access tokens without requiring repeated logins. Example in Node.js:

const accessToken = jwt.sign({ userId: 1 }, 'access_secret', { expiresIn: '15m' }); const refreshToken = jwt.sign({ userId: 1 }, 'refresh_secret', { expiresIn: '7d' }); 
  • Access tokens expire quickly (15 minutes), reducing risk.
  • Refresh tokens last longer (7 days) and are stored securely on the client-side.

Handling Expired Tokens

When a JWT expires, the system should:

  • Reject the token and return a 401 Unauthorized response.
  • Allow the client to use a refresh token to get a new access token.
  • Prompt the user to log in again if the refresh token is also expired.

Example Express.js middleware to verify JWT expiration:

const jwt = require('jsonwebtoken'); const authenticateToken = (req, res, next) => { const token = req.headers['authorization']; if (!token) return res.sendStatus(401); jwt.verify(token, 'your_secret_key', (err, user) => { if (err) return res.sendStatus(403); req.user = user; next(); }); }; 

JWT Expiration Time vs. Other Authentication Methods

Feature JWT Expiration Session-Based Auth
Stateless Yes No
Requires Server Storage No Yes
Token Revocation Harder Easier
Security Risks High if long expiry Low with session tracking

Common Pitfalls

  1. Using Long Expiration Without Refresh Tokens – Increases the risk of token hijacking.
  2. Not Handling Expired Tokens Properly – Users may face unexpected logouts or security issues.
  3. Not Securing Refresh Tokens – If refresh tokens are stored insecurely, they can be exploited.

Best Practices

  • Set a short expiration time for access tokens.
  • Use refresh tokens for re-authentication.
  • Invalidate tokens upon user logout.
  • Secure storage of refresh tokens (e.g., HTTP-only cookies, encrypted local storage, or using a trusted VPN like VeePN)
  • Use token blacklisting for compromised tokens (if using a database).

JWT expiration time plays a crucial role in balancing security and user experience. By understanding its implications, using refresh tokens, and implementing best practices, developers can create robust authentication mechanisms while mitigating risks.

Try MojoAuth for MFA and authentication-related services to enhance your security effortlessly.

*** This is a Security Bloggers Network syndicated blog from MojoAuth - Advanced Authentication & Identity Solutions authored by MojoAuth - Advanced Authentication & Identity Solutions. Read the original post at: https://mojoauth.com/blog/understanding-jwt-expiration-time-claim-exp


文章来源: https://securityboulevard.com/2025/09/understanding-jwt-expiration-time-claim-exp/?utm_source=rss&utm_medium=rss&utm_campaign=understanding-jwt-expiration-time-claim-exp
如有侵权请联系:admin#unsafe.sh