Junior — Middle
How is the validity period of a JWT counter set and configured?
sobes.tech AI
Answer from AI
The validity period of a JWT (JSON Web Token) is set using the standard exp (expiration time) field, which indicates the token's expiration time in UNIX timestamp format (the number of seconds since January 1, 1970).
When creating a JWT in Python, for example using the PyJWT library, you can specify the token's lifetime as follows:
import jwt
import datetime
payload = {
'user_id': 123,
'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1) # token is valid for 1 hour
}
secret = 'your_secret_key'
token = jwt.encode(payload, secret, algorithm='HS256')
Here, exp is set to the current time plus 1 hour, after which the token is considered expired and invalid. When verifying the token, the library automatically checks the exp field and rejects expired tokens.