Generate Access Token with PyJWT

  • Share this:

Code introduction


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


Technology Stack : PyJWT, datetime

Code Type : Function

Code Difficulty : Intermediate


                
                    
import jwt
import datetime
import random

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