You can download this code by clicking the button below.
This code is now available for download.
Generates a JWT token with username and expiration time.
Technology Stack : PyJWT, datetime
Code Type : Authentication
Code Difficulty : Intermediate
import jwt
import datetime
def generate_token(username, secret_key):
# The expiration time of the token
expiration_time = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
# Create a payload with username and expiration time
payload = {
'username': username,
'exp': expiration_time
}
# Encode the payload with the secret key and algorithm
token = jwt.encode(payload, secret_key, algorithm='HS256')
return token
# JSON description of the function