Generate JWT Token with Expiration Time

  • Share this:

Code introduction


This function generates a JWT (JSON Web Token) using the PyJWT library, which includes the username and expiration time.


Technology Stack : PyJWT, datetime

Code Type : Function

Code Difficulty : Intermediate


                
                    
import jwt
import datetime

def generate_jwt_token(username, secret_key):
    expiration_time = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
    payload = {
        'username': username,
        'exp': expiration_time
    }
    token = jwt.encode(payload, secret_key, algorithm='HS256')
    return token                
              
Tags: