Generate Secure JWT Token with User ID and Audience

  • Share this:

Code introduction


This function uses the JWT module from the Authlib library to generate a secure token based on the HS256 algorithm. It accepts user ID and audience as parameters and signs it with a key.


Technology Stack : Authlib, JWT

Code Type : Function

Code Difficulty : Intermediate


                
                    
def generate_random_token(user_id, audience):
    from authlib.jose import jwt
    from authlib.jose import JWTError

    try:
        token = jwt.encode({
            'user_id': user_id,
            'audience': audience
        }, 'your_secret_key', algorithm='HS256')
        return token
    except JWTError as e:
        return str(e)                
              
Tags: