JSON Web Token (JWT)is a lightweight security token based on the JSON format, usually used for authentication and information exchange. Python'sPyJWTis a popular library for handling JWT. This article will start from scratch and take you to gradually learn the basic usage, principles and advanced functions of PyJWT.
What is JWT
The composition of JWT
JWT is a three-part string:
- Header (header): Declaration type and signature algorithm.
- Payload: Store data (usually user information or statement).
- Signature: Sign the Header and Payload to ensure that the data has not been tampered with.
They pass.
Separation, the overall form is:
For example:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMjMsIm5hbWUiOiJKb2UiLCJyb2xlIjoiYWRtaW4ifQ.4zUHL8hfXX8E8OomNQByT3MHnfoyQh27-8r1ZjXv9Fo
JWT's workflow
- Generate tokens: When the user logs in, the server verifies the user's identity and generates a JWT.
-
Carrying a token: JWT usually passes through HTTP Header
Authorization
Field pass. - Verify token: After the server receives the request, it verifies whether the JWT signature is valid and confirms that the information has not been tampered with.
Install PyJWT
Before you start using PyJWT, install it:
pip install PyJWT
Generate JWT
Create a simple JWT
Here is how to use PyJWT to generate a simple JWT:
import jwt import datetime # Define keys and algorithmsSECRET_KEY = "your_secret_key" ALGORITHM = "HS256" # Generate JWTpayload = { "user_id": 123, "name": "John Doe", "role": "admin", "exp": () + (hours=1) # Set expiration time} token = (payload, SECRET_KEY, algorithm=ALGORITHM) print("Generated JWT:", token)
Code description:
-
payload
is the load, whereexp
It is the expiration time. -
Used to generate JWT.
Decode JWT
To decode the generated JWT and view the data:
decoded_payload = (token, SECRET_KEY, algorithms=[ALGORITHM]) print("Decoded Payload:", decoded_payload)
Check expiration date
If the token expires, it will be thrownException:
try: decoded_payload = (token, SECRET_KEY, algorithms=[ALGORITHM]) print("Decoded Payload:", decoded_payload) except : print("Token has expired!")
JWT signature and verification
PyJWT supports a variety of algorithms, such as:
- Symmetrical algorithm:
HS256
,HS384
,HS512
- Asymmetric algorithm:
RS256
,ES256
Symmetric encryption
Symmetric encryption uses a single key signature and verification:
# Symmetric encryption signaturetoken = (payload, SECRET_KEY, algorithm="HS256") # Verify the signaturedecoded_payload = (token, SECRET_KEY, algorithms=["HS256"])
Asymmetric encryption
Asymmetric encryption uses public and private keys. Example:
Generate a key(Suppose there is an RSA key pair).
-
Signature and Verification:
private_key = open("private_key.pem").read() public_key = open("public_key.pem").read() # Sign with private keytoken = (payload, private_key, algorithm="RS256") # Verify using public keydecoded_payload = (token, public_key, algorithms=["RS256"])
Advanced features
Custom statement
In addition to standard statements (such asexp
、iat
), you can add custom fields:
payload = { "user_id": 123, "role": "editor", "permissions": ["read", "write"], "iat": (), # Issuance time "exp": () + (days=1) # Expiry time} token = (payload, SECRET_KEY, algorithm="HS256")
Set expiration time
exp
is a standard declaration of JWT, used to specify the expiration time.
payload = { "user_id": 123, "exp": () + (minutes=15) }
Token refresh
Token refresh can extend the user's login session time:
# Original Tokentoken = (payload, SECRET_KEY, algorithm="HS256") # Decode and refreshdecoded = (token, SECRET_KEY, algorithms=["HS256"], options={"verify_exp": False}) decoded["exp"] = () + (minutes=15) # Generate a new tokenrefreshed_token = (decoded, SECRET_KEY, algorithm="HS256")
Common errors and solutions
Token expired
error message:
Solution:existCatch exceptions when .
try: decoded_payload = (token, SECRET_KEY, algorithms=[ALGORITHM]) except : print("Token has expired!")
Signature verification failed
error message:
Solution: Make sure the signature key is correct and use the same algorithm.
Practical: JWT authentication example
Here is a Fastapi-based example that implements user login and token verification:
from fastapi import FastAPI, Depends, HTTPException from import OAuth2PasswordBearer, OAuth2PasswordRequestForm import jwt import datetime from typing import Dict, Optional # ========================== #Configuration and Constants# ========================== SECRET_KEY = "your_secret_key" # JWT KeyALGORITHM = "HS256" # JWT AlgorithmTOKEN_EXPIRE_HOURS = 1 # Token valid time (hours) # OAuth2PasswordBearer definition, used to obtain the user's tokenoauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") # ========================== # User Services# ========================== class UserService: """ User Service Class: Responsible for user authentication and management """ def __init__(self): # Simulate database: username and password self.users_db = { "admin": "password123", "user": "mypassword" } def authenticate(self, username: str, password: str) -> bool: """ Verify that the username and password match :param username: Username :param password: Password :return: Verify whether it is successful """ return self.users_db.get(username) == password # ========================== # JWT Tools# ========================== class JWTHandler: """ JWT Tool Class: Responsible for generating and verifying JWT """ @staticmethod def create_token(username: str, expire_hours: int = TOKEN_EXPIRE_HOURS) -> str: """ Generate JWT :param username: Username :param expire_hours: Token validity time :return: The generated JWT string """ payload = { "sub": username, # Declare the subject "exp": () + (hours=expire_hours) # Expiry time } return (payload, SECRET_KEY, algorithm=ALGORITHM) @staticmethod def verify_token(token: str) -> Optional[Dict]: """ Verify the JWT and decode it :param token: JWT string :return: Decoded Payload, if invalid, returns None """ try: return (token, SECRET_KEY, algorithms=[ALGORITHM]) except : raise HTTPException(status_code=401, detail="Token expired") except : raise HTTPException(status_code=401, detail="Invalid token") # ========================== # Dependency injection class# ========================== class Dependencies: """ Dependency injection class, used to decouple dependencies """ def __init__(self, user_service: UserService, jwt_handler: JWTHandler): self.user_service = user_service self.jwt_handler = jwt_handler def authenticate_user(self, form_data: OAuth2PasswordRequestForm) -> str: """ Verify the user and generate JWT :param form_data: User submitted form data (including username and password) :return: JWT """ username = form_data.username password = form_data.password if not self.user_service.authenticate(username, password): raise HTTPException(status_code=401, detail="Error in username or password") return self.jwt_handler.create_token(username) def validate_token(self, token: str) -> str: """ Verify the token and return the username :param token: JWT :return: The decoded username """ payload = self.jwt_handler.verify_token(token) username = ("sub") if not username: raise HTTPException(status_code=401, detail="Invalid Token") return username # ========================== # Create a FastAPI application# ========================== app = FastAPI() # Instantiate the service classuser_service = UserService() jwt_handler = JWTHandler() dependencies = Dependencies(user_service, jwt_handler) # ========================== #Route definition# ========================== @("/token") async def login(form_data: OAuth2PasswordRequestForm = Depends()): """ Login interface: Verify the user and return to Token :param form_data: OAuth2PasswordRequestForm provided by FastAPI :return: JSON containing Token """ token = dependencies.authenticate_user(form_data) return {"access_token": token, "token_type": "bearer"} @("/protected") async def protected(token: str = Depends(oauth2_scheme)): """ Protected interface: A valid token is required to access it :param token: OAuth2PasswordBearer Automatically extracted JWT :return: Welcome message """ username = dependencies.validate_token(token) return {"message": f"Welcome back,{username}!Your access has been authorized。"} # ========================== # Main program entry (debug only)# ========================== if __name__ == "__main__": import uvicorn (app, host="127.0.0.1", port=8000)
Code description
-
FastAPI's OAuth2PasswordBearer
-
OAuth2PasswordBearer
is a tool provided by FastAPI to automatically extract and verify Bearer type tokens from request headers. - pass
Depends(oauth2_scheme)
Tokens can be easily obtained in the route.
-
-
JWT generation and decoding
- use
Generate a JWT containing user information.
- use
Verify and decode the JWT and handle possible exceptions such as the token expires or is invalid.
- use
-
Routing instructions
-
/token
: Used to log in, verify username and password, and return to the token. -
/protected
: Protected interface, accessible only to users who provide valid tokens.
-
-
Error handling
- If the user's username or password is incorrect, an error of 401 will be returned.
- If the token is invalid or expires, a 401 error will also be returned.
Test process
-
Installation dependenciesMake sure to be installed
fastapi
anduvicorn
:pip install fastapi uvicorn PyJWT
Start the serviceAfter running the code, visit
http://127.0.0.1:8000/docs
Open the API document page automatically generated by FastAPI.-
Test interface
-
Login interfaceuse
/token
, submit the username and password to obtain the token. -
Protected interfaceuse
/protected
, add in the request headerAuthorization: Bearer <token>
Come to visit.
-
Login interfaceuse
Summarize
In this article, we dive into the fundamentals of JSON Web Token (JWT), especially how to use the PyJWT library to generate, decode, and verify tokens. We first understand the working mechanism of JWT and learn the signature algorithm and its advanced functions to ensure the security and reliability of the token. In addition, we have discussed some common problems and their solutions to help you better address these challenges that may be encountered in real-world applications. Finally, we combine theory with practice through a complete JWT authentication example, hoping to provide valuable reference for your project. After mastering these contents, you will be able to flexibly apply JWT in your web applications, improving the security and user experience of your system.
This is the end of this article about PyJWT token verification. For more related PyJWT token verification content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!