Help
Community
Project privacy set to public. By default, its content is available to everyone (authenticated or not). Please note that more restrictive permissions might exist on some items.
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)
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.
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.
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.
jwt.encode() generates a JWT by encrypting the payload with:
Secret key (SECRET_KEY) → used for security.
Algorithm ("HS256") → a hashing method to ensure security.
The result is a signed, secure token.
Calls the create_jwt() function to generate a JWT.
Prints the JWT string, which can be sent to users for authentication.
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
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