JWT (JSON Web Token) is a token format commonly used to maintain authenticated sessions in APIs.
After a user successfully authenticates, the server can generate a JWT containing information about the user. This token can then be used for authenticated API requests.
Code
import jwt
SECRET_KEY = "my-secret-key"
payload = {
"user_id": 1
}
token = jwt.encode(
payload,
SECRET_KEY,
algorithm="HS256"
)
print(token)
Understanding the Code
1. Import JWT
First, import the JWT library:
import jwt
2. Define the Secret Key
A secret key is used to sign the token:
SECRET_KEY = "my-secret-key"
The secret key should be kept secure in a real application.
3. Create the Payload
The payload contains information that will be stored in the token:
payload = {
"user_id": 1
}
In this example, the payload contains the user’s ID.
4. Generate the Token
Use jwt.encode() to create the JWT:
token = jwt.encode(
payload,
SECRET_KEY,
algorithm="HS256"
)
The token is created using:
- The payload
- The secret key
- The
HS256signing algorithm
5. Print the Token
print(token)
This displays the generated JWT.
Output
The generated token will look similar to:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
JWT Flow
A basic JWT authentication flow looks like:
User Login
↓
Verify Credentials
↓
Create JWT
↓
Return Token
↓
Client Uses Token
↓
Authenticated API Requests
Summary
JWT provides a token-based way to maintain authenticated sessions in APIs.
The basic process is:
payload = {
"user_id": 1
}
token = jwt.encode(
payload,
SECRET_KEY,
algorithm="HS256"
)