jwt token in python

JSON Web Tokens (JWT) are a widely used format for token-based authentication. Here's an example of how to create and verify JWT tokens in Python using the PyJWT library:

main.py
import jwt

# Define a secret key to sign the JWT with
SECRET_KEY = 'my-secret-key'

# Define a payload for the JWT
payload = {"user_id": 1234}

# Encode the JWT using the secret key and payload
jwt_token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')

# Print the encoded JWT
print(jwt_token)

# Decode and verify the JWT using the secret key
decoded_payload = jwt.decode(jwt_token, SECRET_KEY, algorithms=['HS256'])

# Print the decoded payload
print(decoded_payload)
476 chars
20 lines

In this example, we first define a secret key to sign the JWT with. We then create a payload containing some user data. We then use the jwt.encode() method to encode the token using the payload and secret key. We print the encoded JWT token to the console.

To decode and verify the JWT token, we use the jwt.decode() method, passing in the encoded token, the secret key, and a list of acceptable algorithms for signature verification. This method returns the decoded payload, which we can then print to the console.

gistlibby LogSnag