JWT Token Generator with Username and Expiry

  • Share this:

Code introduction


Generates a JWT token with username and expiration time.


Technology Stack : PyJWT, datetime

Code Type : Authentication

Code Difficulty : Intermediate


                
                    
import jwt
import datetime

def generate_token(username, secret_key):
    # The expiration time of the token
    expiration_time = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
    # Create a payload with username and expiration time
    payload = {
        'username': username,
        'exp': expiration_time
    }
    # Encode the payload with the secret key and algorithm
    token = jwt.encode(payload, secret_key, algorithm='HS256')
    return token

# JSON description of the function                
              
Tags: