You can download this code by clicking the button below.
This code is now available for download.
This function generates a JWT token using the HS256 algorithm. The token includes the username and an expiration time, with a validity of 1 hour.
Technology Stack : PyJWT, datetime
Code Type : Function
Code Difficulty : Intermediate
import jwt
import datetime
import random
def generate_jwt_token(username, secret_key):
# Generate a JWT token for a given username
expiration_time = datetime.datetime.utcnow() + datetime.timedelta(hours=1) # Token expires in 1 hour
payload = {
'username': username,
'exp': expiration_time
}
token = jwt.encode(payload, secret_key, algorithm='HS256')
return token
# JSON explanation of the code