You can download this code by clicking the button below.
This code is now available for download.
This custom function generates a JWT token that includes a username and an expiration time, signed using the HS256 algorithm. To use this function, you need to provide a username and a secret key.
Technology Stack : PyJWT, datetime, os
Code Type : Custom function
Code Difficulty : Intermediate
import jwt
import datetime
import os
def generate_token(username, secret_key):
payload = {
'username': username,
'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1) # Token expires in 1 hour
}
token = jwt.encode(payload, secret_key, algorithm='HS256')
return token