You can download this code by clicking the button below.
This code is now available for download.
This function generates a JWT token for a given user_id, including an expiration time set to 1 hour from the current time. The token is encoded using the HS256 algorithm with a secret key.
Technology Stack : PyJWT, datetime, random
Code Type : Python Function
Code Difficulty : Intermediate
import jwt
import datetime
import random
def generate_token(user_id, secret_key):
# Create a payload with expiration time set to 1 hour from now
payload = {
'user_id': user_id,
'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)
}
# Generate a token using the JWT library
token = jwt.encode(payload, secret_key, algorithm='HS256')
return token
# Code Explanation
# This function generates a JWT token for a given user_id. It sets the expiration time to 1 hour from the current time. The token is encoded using the HS256 algorithm with a secret key.
# JSON Explanation