Welcome to our comprehensive guide on JWT (JSON Web Tokens) in Python! In this tutorial, we'll explore JWT tokens, their importance, and how to use them in your Python projects. Let's dive right in!
JWT tokens are a popular method for handling authentication and authorization in web applications. They consist of three parts: header, payload, and signature.
The header contains metadata about the token, such as the token type (JWT) and the algorithm used to sign the token.
{
"alg": "HS256",
"typ": "JWT"
}The payload contains the actual data, such as user ID, roles, and expiration time.
{
"user_id": 12345,
"exp": 1632499200
}The signature ensures the integrity of the token and verifies that the sender is trustworthy. It is generated by combining the header, payload, and a secret key.
Now, let's see how to create a JWT token in Python using the pyjwt library.
pip install pyjwtFirst, let's create a secret key for our application.
import secrets
SECRET_KEY = secrets.token_hex(32)Next, let's encode our payload using the encode() function from pyjwt.
import jwt
import datetime
def create_jwt(user_id):
payload = {
'user_id': user_id,
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)
}
encoded_jwt = jwt.encode(
payload,
SECRET_KEY,
algorithm='HS256'
)
return encoded_jwtNow, let's create a function to decode and validate the JWT token.
def decode_jwt(encoded_jwt):
try:
decoded_jwt = jwt.decode(
encoded_jwt,
SECRET_KEY,
algorithms=['HS256']
)
return decoded_jwt
except jwt.ExpiredSignatureError:
return {"error": "Expired token"}
except jwt.InvalidTokenError:
return {"error": "Invalid token"}Now, let's create a simple example where we create a token, store it in a cookie, and then retrieve it to verify the user's identity.
from flask import Flask, request, jsonify, make_response
app = Flask(__name__)
app.config['SECRET_KEY'] = SECRET_KEY
@app.route('/login', methods=['POST'])
def login():
user_id = request.json.get('user_id')
if user_id:
jwt_token = create_jwt(user_id)
response = make_response()
response.set_cookie('token', jwt_token)
return jsonify({'message': 'Logged in'})
return jsonify({'error': 'Invalid user_id'})
@app.route('/verify', methods=['GET'])
def verify():
token = request.cookies.get('token')
if token:
decoded_token = decode_jwt(token)
if 'error' not in decoded_token:
return jsonify({'user_id': decoded_token['user_id']})
return jsonify({'error': 'Invalid or expired token'})What are the three parts of a JWT token?
We hope you enjoyed this comprehensive guide on JWT tokens in Python! In the next lesson, we'll dive deeper into using JWT tokens in a real-world web application. Happy coding! 🚀