You can download this code by clicking the button below.
This code is now available for download.
This function generates a JWT token based on the HS256 algorithm, including the username and an expiration timestamp in 1 hour.
Technology Stack : PyJWT, datetime
Code Type : Function
Code Difficulty : Intermediate
import jwt
import random
import datetime
def generate_random_token(username, secret_key):
payload = {
'username': username,
'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1) # Token expires in 1 hour
}
token = jwt.encode(payload, secret_key, algorithm='HS256')
return token