Junior — Middle
How can you verify that a JWT token is valid and active?
sobes.tech AI
Answer from AI
To verify the validity and activity of a JWT token, several steps need to be taken:
-
Signature verification: Using a secret key (for HMAC) or a public key (for RSA/ECDSA), verify that the token's signature is correct and has not been altered.
-
Expiration check: Check the
exp(expiration time) andnbf(not before) fields to ensure the token has not expired and is active. -
Other claims verification: For example,
iss(issuer),aud(audience) — to ensure the token is intended for your application.
An example in Python using the PyJWT library:
import jwt
from jwt import ExpiredSignatureError, InvalidTokenError
secret = 'your-secret-key'
token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...'
try:
payload = jwt.decode(token, secret, algorithms=['HS256'], audience='your-audience')
# Token is valid and active
print('Payload:', payload)
except ExpiredSignatureError:
print('Token has expired')
except InvalidTokenError:
print('Invalid token')
Thus, the validity of a JWT is determined by signature and expiration checks, and activity by matching the current time with the token's constraints.