generate json web token in python

To generate a JSON Web Token (JWT) in Python, you can use the PyJWT library. Here's an example of how to do it:

main.py
import jwt

# Define the payload and the secret key
payload = {'user_id': 1234, 'email': 'user@example.com'}
secret_key = 'my_secret_key'

# Generate the JWT
jwt_token = jwt.encode(payload, secret_key, algorithm='HS256')

# Print the token
print(jwt_token)
257 chars
12 lines

In this example, we first import the jwt module from the PyJWT library. We then define the payload, which is a dictionary containing some data that we want to include in the token (in this case, a user ID and an email address), as well as the secret key that we'll use to sign the token.

We then call the jwt.encode method, passing in the payload, secret key, and the algorithm we want to use to sign the token (in this case, HMAC with SHA-256). This returns the JWT as a byte string.

Finally, we print the token to the console.

Note that you'll want to keep your secret key secure, as it is used to sign and verify the token. Also, when decoding the token later on, you'll need to use the same secret key to verify the signature.

gistlibby LogSnag