Access Token Generation with JWT

  • Share this:

Code introduction


This function generates a valid access token containing the username and expiration time, signed using the HS256 algorithm.


Technology Stack : PyJWT, datetime

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
import jwt
import random
from datetime import datetime, timedelta

def generate_access_token(username, secret_key):
    # Define the algorithm to be used for the token
    algorithm = 'HS256'
    
    # Define the expiration time for the token
    expiration_time = datetime.utcnow() + timedelta(hours=1)
    
    # Create a payload for the token
    payload = {
        'username': username,
        'exp': expiration_time
    }
    
    # Generate the access token
    access_token = jwt.encode(payload, secret_key, algorithm=algorithm)
    
    return access_token

# JSON representation of the code                
              
Tags: