Python jwt token example

Selina 93 Published: 11/24/2024

Python jwt token example

Python JWT Token Example!

JSON Web Tokens (JWT) are a widely used standard for securely transmitting information between two parties as JSON objects. The process involves signing the payload with a private key, which ensures its authenticity and integrity.

Let's dive into a Python example to create, verify, and use JWT tokens:

Step 1: Install required libraries

You'll need pyjwt (python-jwt) for generating and verifying JWTs. Run the following command:

pip install pyjwt

Step 2: Generate a private key and public key pair using RSA algorithm

Create a new directory for your project, and create a file named rsa_keys.py. Add the following code to generate RSA keys (private and public):

import rsa

private_key, public_key = rsa.newkeys(512)

Save the generated keys for later use

with open('private_key.pem', 'wb') as f:

f.write(private_key.save_pkcs1(password='my_secret_password'))

with open('public_key.pem', 'wb') as f:

f.write(public_key.save_pkcs1())

This code generates a 512-bit RSA key pair using the rsa library. The private key is saved with a password ('my_secret_password') for security, while the public key is saved without any protection.

Step 3: Create a JWT payload and sign it with your private key

Create a new file named jwt_example.py, where you'll define the following functions:

import datetime

import jwt

Load the generated private key

with open('private_key.pem', 'rb') as f:

private_key = rsa.import_pkcs1(f.read(), password='my_secret_password')

def generate_jwt(payload):

Set the expiration time (1 hour from now)

expires_at = datetime.datetime.now() + datetime.timedelta(hours=1)

Generate a JWT token

return jwt.encode(payload, private_key, algorithm='RS256', headers={'exp': str(expires_at)})

Define the payload for our JWT token

payload = {'user_id': '1234567890', 'email': '[email protected]'}

Generate and print the signed JWT token

jwt_token = generate_jwt(payload)

print(jwt_token)

This code defines a generate_jwt function that creates a JSON Web Token (JWT) with a payload, which is then signed using your private RSA key. The expiration time is set to 1 hour from now. The payload dictionary contains user data (in this case, user ID and email). When you run the script, it prints the generated JWT token.

Step 4: Verify the JWT token using your public key

Create another file named jwt_verify.py, where you'll define the following function:

import jwt

def verify_jwt(jwt_token):

Load the generated public key

with open('public_key.pem', 'rb') as f:

public_key = rsa.import_pkcs1(f.read())

try:

Verify the JWT token using your public key

payload = jwt.decode(jwt_token, public_key, algorithms=['RS256'])

print("JWT token is valid!")

except Exception as e:

print(f"Invalid or expired JWT: {e}")

Use the verify_jwt function with the generated JWT token

verify_jwt(jwt_token)

This code defines a verify_jwt function that takes a JWT token and verifies it using your public RSA key. If the token is valid, it prints a success message; otherwise, it prints an error message.

Conclusion

That's it! You've now learned how to generate, sign, and verify JSON Web Tokens (JWTs) in Python using the pyjwt library and RSA keys. This demonstrates the basics of JWT security and usage. Keep practicing, and soon you'll be a master of token authentication!

(Note: I intentionally omitted error handling and input validation for simplicity. In a real-world scenario, you should always handle errors and validate inputs thoroughly.)

Python jwt token github

Here is the information you requested on using JSON Web Tokens (JWT) with Python and GitHub:

What is JWT?

JSON Web Tokens (JWT) are a way to securely transmit data between two parties, such as a user and an API server. A JWT is a digitally signed, compact representation of claims that can be verified and trusted. It's commonly used for authentication and authorization.

How does JWT work with Python?

In Python, you can use libraries like pyjwt to generate and verify JWTs. Here's a simple example:

import jwt

import datetime

def create_token(user_id):

payload = {

'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30),

'iat': datetime.datetime.utcnow(),

'sub': user_id,

}

return jwt.encode(payload, 'my_secret_key', algorithm='HS256')

print(create_token(123))

In this example, we're creating a JWT that contains the user ID and two timestamps (expiration and issued at). The jwt.encode() function takes three arguments: the payload (our JSON data), the secret key (used for signing the token), and the algorithm (in this case, HS256).

How does JWT work with GitHub?

GitHub provides an API that uses JWTs to authenticate and authorize requests. Here's how you can use JWTs with GitHub:

Generate a JWT: You'll need to generate a JWT using your secret key (e.g., client_id and client_secret). For example, using the pyjwt library:
import jwt

import datetime

def create_token(client_id, client_secret):

payload = {

'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30),

'iat': datetime.datetime.utcnow(),

'iss': client_id,

}

return jwt.encode(payload, client_secret, algorithm='HS256')

token = create_token('your_client_id', 'your_client_secret')

Use the JWT to authenticate with GitHub: When making API requests, include your JWT in the Authorization header:
import requests

headers = {

'Authorization': f'Bearer {token}',

'Accept': 'application/vnd.github.v3+json',

}

response = requests.get('https://api.github.com/repos/octocat/hello-world', headers=headers)

print(response.json())

In this example, we're making a GET request to the GitHub API with the JWT included in the Authorization header. The Bearer scheme indicates that the token should be used for authentication.

Conclusion

JSON Web Tokens (JWT) are a powerful way to securely transmit data between two parties, including authenticating and authorizing requests. By using libraries like pyjwt and following GitHub's API guidelines, you can use JWTs with Python to interact with the GitHub API.