Random Expiration JWT Token Generator

  • Share this:

Code introduction


This function generates a JWT token with a randomly set expiration time.


Technology Stack : PyJWT, datetime, random

Code Type : Function

Code Difficulty : Intermediate


                
                    
import jwt
import random
import datetime

def generate_random_jwt_token(key, payload, exp_delta_seconds=3600):
    """
    Generate a JWT token with a random expiration time.

    Args:
    key (str): The secret key used to encode the token.
    payload (dict): The payload data to be encoded in the token.
    exp_delta_seconds (int): The number of seconds to add to the current time to set the expiration time.

    Returns:
    str: The generated JWT token.
    """
    # Generate a random expiration time
    exp = datetime.datetime.utcnow() + datetime.timedelta(seconds=exp_delta_seconds + random.randint(0, 3600))
    
    # Encode the payload with the secret key and set the expiration time
    token = jwt.encode(payload, key, algorithm='HS256', expires_at=exp)
    
    return token