JWT Tokens in Python Tutorial 🎯

beginner
5 min

JWT Tokens in Python Tutorial 🎯

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!

Understanding JWT Tokens 📝

JWT tokens are a popular method for handling authentication and authorization in web applications. They consist of three parts: header, payload, and signature.

Header

The header contains metadata about the token, such as the token type (JWT) and the algorithm used to sign the token.

python
{ "alg": "HS256", "typ": "JWT" }

Payload

The payload contains the actual data, such as user ID, roles, and expiration time.

python
{ "user_id": 12345, "exp": 1632499200 }

Signature

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.

Creating JWT Tokens 💡

Now, let's see how to create a JWT token in Python using the pyjwt library.

bash
pip install pyjwt

Creating a Secret Key

First, let's create a secret key for our application.

python
import secrets SECRET_KEY = secrets.token_hex(32)

Encode a Payload

Next, let's encode our payload using the encode() function from pyjwt.

python
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_jwt

Decoding JWT Tokens 💡

Now, let's create a function to decode and validate the JWT token.

python
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"}

Putting it all together 💡

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.

python
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'})

Quiz 💡

Quick Quiz
Question 1 of 1

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! 🚀