Generate Access Token with User ID and Expiration Time

  • Share this:

Code introduction


This function generates an access token based on the HS256 algorithm, which includes user ID and expiration time.


Technology Stack : PyJWT, datetime

Code Type : Function

Code Difficulty : Intermediate


                
                    
import jwt
import datetime
import random

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