PyJWT Access Token Generator with Expiry

  • Share this:

Code introduction


This function generates an access token using the PyJWT library, which includes the username and an expiration time.


Technology Stack : PyJWT, datetime

Code Type : Custom function

Code Difficulty : Intermediate


                
                    
import jwt
import datetime
import random

def generate_access_token(username, secret_key):
    """
    This function generates an access token using PyJWT library.
    The token includes the username and an expiration time.
    """
    payload = {
        'username': username,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)
    }
    token = jwt.encode(payload, secret_key, algorithm='HS256')
    return token                
              
Tags: