Junior — Middle
How long is a JWT token valid before it expires?
sobes.tech AI
Answer from AI
The validity period of a JWT (JSON Web Token) is set in its payload using the exp (expiration time) field. This field contains a timestamp (usually in UNIX timestamp format), after which the token is considered invalid.
The token's validity period is not fixed by language or standard — it is determined when the token is generated and depends on the application's security requirements. For example, a token may be valid:
- For a few minutes (e.g., 15 minutes) for increased security.
- For several hours or days if longer access is required.
An example of setting the expiration time using the PyJWT library:
import jwt
import datetime
payload = {
'user_id': 123,
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30) # token is valid for 30 minutes
}
token = jwt.encode(payload, 'secret_key', algorithm='HS256')
Thus, the validity period of a JWT token is determined at its creation and can be configured depending on security requirements.