You can download this code by clicking the button below.
This code is now available for download.
This function generates an access token using the PyJWT library, which includes a user ID and an expiration time. The token is signed using the HS256 algorithm.
Technology Stack : PyJWT, JWT, HS256, datetime
Code Type : Function
Code Difficulty : Intermediate
import jwt
import datetime
import random
def generate_access_token(user_id, secret_key):
"""
Generate an access token using PyJWT.
Args:
user_id (int): The user ID to be encoded in the token.
secret_key (str): The secret key to sign the token with.
Returns:
str: The generated access token.
"""
payload = {
'user_id': user_id,
'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1) # Token expires in 1 hour
}
token = jwt.encode(payload, secret_key, algorithm='HS256')
return token