How to decode JWT using Python?
How to decode JWT using Python?
Decoding a JSON Web Token (JWT) in Python involves using the jwt
library, which is available on PyPI. Here's a step-by-step guide:
Step 1: Install the jwt
library
You can install the jwt
library using pip:
pip install pyjwt
Step 2: Import the jwt
library and load the JWT token
In your Python script, import the jwt
library and load the JWT token:
import jwt
Load the JWT token from a file or database
with open('token.txt', 'r') as f:
token = f.read()
print(token)
Assuming you have the JWT token in a file named token.txt
, we'll use that as an example.
Step 3: Decode the JWT token
Decode the JWT token using the jwt.decode()
function. You need to specify the algorithm used to encode the token, which is typically HS256
(HMAC with SHA-256):
decoded_token = jwt.decode(token, 'your_secret_key', algorithms=['HS256'])
print(decoded_token)
Replace 'your_secret_key'
with your actual secret key.
Step 4: Verify the decoded token
The decoded token is a Python dictionary containing the token's claims (e.g., user ID, email). You can verify that the token has been correctly decoded by checking its contents:
print(decoded_token['user_id']) # Output: user's ID
print(decoded_token['email']) # Output: user's email
Step 5: Verify the token's signature
To ensure the token hasn't been tampered with, you can verify its digital signature using the jwt.verify()
function:
verified = jwt.verify(token, 'your_secret_key', algorithms=['HS256'])
if verified:
print('Token is valid and not tampered with.')
else:
print('Token is invalid or tampered with.')
Putting it all together
Here's a complete example script that decodes and verifies a JWT token:
import jwt
Load the JWT token from a file or database
with open('token.txt', 'r') as f:
token = f.read()
print(token)
Decode the JWT token
decoded_token = jwt.decode(token, 'your_secret_key', algorithms=['HS256'])
print(decoded_token)
Verify the decoded token
print(decoded_token['user_id']) # Output: user's ID
print(decoded_token['email']) # Output: user's email
Verify the token's signature
verified = jwt.verify(token, 'your_secret_key', algorithms=['HS256'])
if verified:
print('Token is valid and not tampered with.')
else:
print('Token is invalid or tampered with.')
Remember to replace 'your_secret_key'
with your actual secret key.
How to create a JWT token in Python?
To create a JSON Web Token (JWT) in Python, you can use the pyjwt
library, which is a popular and well-maintained package for working with JWTs.
Here's an example of how to use pyjwt
to create a JWT token:
First, install the pyjwt
library using pip:
pip install pyjwt
Next, import the necessary modules and functions from pyjwt
:
import jwt
from datetime import datetime, timedelta
Set the secret key for signing the token
SECRET_KEY = 'your_secret_key_here'
Set the expiration time for the token (1 hour in this example)
EXPIRATION_TIME = timedelta(hours=1)
Create a dictionary to store the user's claims (e.g., username, email, etc.)
user_claims = {
'username': 'john_doe',
'email': '[email protected]'
}
Now, create the JWT token using the encode()
function from pyjwt
:
# Create a payload dictionary with the user's claims and the current timestamp
payload = {
'iat': datetime.utcnow(),
'exp': datetime.utcnow() + EXPIRATION_TIME,
**user_claims
}
Sign the token using the secret key
token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
print(token) # Output: a JWT token in compact format (e.g., "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImF1dGhwIjoiMjAxNy0wNyAwMVowMDowMFoiLCJpZGVudGl0eSI6Imh0dHBzOi8vaHR0cHMub3JnLmNvbS91c2VyLmNoZWxsLmRvYnJhbmQuc3RyaW5iYXQuam9uYWxkcnAuaHRtIiwiYXV0aGgiOiJodHRwczovL3d3dy5xdWFsaXRlci5jb20vbGlnaHQtcGFzc3dvcmQiLCJpc3MiOiJkaXNhcHBhZ2UiLCJzdWIiOiI4ZmNkNmEyOTFmMjRjNDExMTAwYTIyMDUifQ.SOME_LONG_SIGNATURE")
print(token.decode('utf-8')) # Output: a JWT token in compact format, decoded and printed as a string
In this example:
We create a dictionarypayload
that contains the user's claims (e.g., username, email) and the current timestamp. We sign the payload using the secret key with the encode()
function from pyjwt
, specifying the algorithm as HS256 (HMAC SHA-256). We print the resulting JWT token in compact format. We also decode and print the token as a string.
That's it! With this example, you should be able to create a JWT token using Python and the pyjwt
library.