•  
      Internship #415158 Creating and Verifying JWT in local machine
    #415158
    Arpita Gumma (arpita.gumma)
    2025-02-12 17:29
    2025-02-12 17:29
    Details
    Creating and Verifying JWT in local machine

    Creation of JWT

    import jwt

    import datetime

    SECREAT_KEY="your_secreat_key"

    def create_jwt():

      payload = {
    
                   "sub": "arpita@gmail.com",
    
                   "exp" : datetime.datetime.utcnow() + datetime.timedelta(minutes=30),
    
                    "iat" : datetime.datetime.utcnow(),
    
             }
    
            token=jwt.encode(payload, SECRET_KEY,  algorithm="HS256")
    
            return token
    

    jwt_token = create_jwt()

    print("generated JWT:",jwt_token)

    1. Import library
    • jwt: It is the PyJWT library used to create and verify JSON Web Tokens.

    • datetime: Used to set the expiration time (exp) and issued-at time (iat) for the token.

    1. Define secret key
    • This is the secret key used to sign and verify the token.

    • Keep this key private, as it is needed to verify the token's authenticity.

    1. Create jwt Function
    • Defines a function create_jwt() that creates and returns a JWT token.
    1. Set payload
    • The payload contains important user information:

    • "sub": Stores the subject (usually user email or user ID).

    • "exp": Expiration time (30 minutes from now). After this time, the token will be invalid.

    • "iat": Issued at (current time) when the token is generated.

    1. Encode the token
    • jwt.encode() generates a JWT by encrypting the payload with:

      1. Secret key (SECRET_KEY) → used for security.

      2. Algorithm ("HS256") → a hashing method to ensure security.

      The result is a signed, secure token.

    1. Return token
    • The function returns the generated token.
    1. Generate and Print the Token
    • Calls the create_jwt() function to generate a JWT.

    • Prints the JWT string, which can be sent to users for authentication.

    Verification of JWT

    def verify_jwt(token):

      try:
    
            decoded_payload= jwt.decode(token,SECRET_KEY,algorithms=["HS256"]
    
             print("Decoded payload:" , decoded_payload)
    
       except jwt.ExpiredSignatureError:
    
             print("Token has expired.")
    
      except jwt.InvalidTokenError:
    
             print("Invalid token.")
    

    verify_jwt(jwt_token)

    1.function to verify JWT

    • defining the function and it takes jwt token as input and varify it
    1. Try to decode the token
    • jwt.decode: this is for decode the token

    • token : the jwt token for verified

    • SECRETS_KEY: is used for encoding

    • algorithm=["HS256"]:hashing algorithm used for verification

    • if decode is successfully then it extract the user data and prints it

    1. Handle expired token error
    • if token has expired then expiredsignitureerror is raised and prints token has expired.
    1. Handle invalid token error
    • if token is incorrect then invalidtokenerror is raised and prints invalid token
    1. call the varification function
    • passing jwt token generated earlier ,and decode the token check the validity
    Empty
    Empty
    State of Progress
    2025-02-11
    Empty
    2025-02-12
    Arpita Gumma (arpita.gumma)
    Ajit kumar (ajit)
    2025-02-12
    Closed
    Attachments
    Empty
    References
    References list is empty