You can download this code by clicking the button below.
This code is now available for download.
This custom function generates a JWT token using the PyJWT library, which includes the user ID and expiration time. It uses a randomly generated secret key for signing the token.
Technology Stack : PyJWT, random
Code Type : Custom function
Code Difficulty : Intermediate
import jwt
import random
import datetime
def generate_random_token(user_id, secret_key):
"""
Generate a random JWT token for a given user ID and secret key.
"""
# Define the expiration time for the token
expiration_time = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
# Create a payload dictionary with user ID and expiration time
payload = {
'user_id': user_id,
'exp': expiration_time
}
# Generate a random secret key for the token
random_secret_key = jwt.utils.base64url_encode(random.randbytes(24))
# Encode the payload with the random secret key
token = jwt.encode(payload, random_secret_key, algorithm='HS256')
return token