Generate JWT Token with User ID and Expiration

  • Share this:

Code introduction


This function uses the PyJWT library to generate a JWT token containing the user ID and expiration time. JWT is an open standard (JSON Web Token) for securely transmitting information over the Internet. This function takes the user ID and secret key as arguments and then creates a token that is valid for 1 hour.


Technology Stack : PyJWT, datetime

Code Type : Authentication

Code Difficulty : Intermediate


                
                    
import jwt
import random
from datetime import datetime, timedelta

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