How to Use JWT (JSON Web Tokens) for API Authentication in Python

 How to Use JWT (JSON Web Tokens) for API Authentication in Python

JWT (JSON Web Tokens) is a compact, URL-safe way to securely transmit information between parties. It is widely used for API authentication and user identity verification in web applications.


This guide shows how to use JWT for API authentication in Python using Flask and the PyJWT library.


πŸ”§ Tools and Libraries You’ll Need

Python 3.x


Flask (a lightweight Python web framework)


PyJWT (pyjwt library for encoding/decoding JWTs)


Install required packages:


bash

Copy

Edit

pip install Flask PyJWT

πŸ” Step-by-Step: Using JWT for API Authentication

1. Setup a Simple Flask API

python

Copy

Edit

from flask import Flask, request, jsonify


app = Flask(__name__)

app.config['SECRET_KEY'] = 'your_secret_key'  # Use a secure, random key

2. Generate JWT on Login

When a user logs in successfully, you return a JWT.


python

Copy

Edit

import jwt

import datetime


@app.route('/login', methods=['POST'])

def login():

    auth_data = request.get_json()

    username = auth_data.get('username')

    password = auth_data.get('password')


    # Simulated user check (replace with real validation)

    if username == 'admin' and password == 'password':

        token = jwt.encode({

            'user': username,

            'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)

        }, app.config['SECRET_KEY'], algorithm='HS256')


        return jsonify({'token': token})

    

    return jsonify({'message': 'Invalid credentials'}), 401

3. Protect Routes with JWT Authentication

Use a decorator to verify the token before granting access.


python

Copy

Edit

from functools import wraps


def token_required(f):

    @wraps(f)

    def decorated(*args, **kwargs):

        token = None


        if 'Authorization' in request.headers:

            token = request.headers['Authorization'].split()[1]  # Bearer <token>


        if not token:

            return jsonify({'message': 'Token is missing!'}), 403


        try:

            data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])

            current_user = data['user']

        except jwt.ExpiredSignatureError:

            return jsonify({'message': 'Token has expired!'}), 401

        except jwt.InvalidTokenError:

            return jsonify({'message': 'Invalid token!'}), 401


        return f(current_user, *args, **kwargs)


    return decorated

4. Create a Protected Route

python

Copy

Edit

@app.route('/protected', methods=['GET'])

@token_required

def protected(current_user):

    return jsonify({'message': f'Hello, {current_user}. You are authenticated!'})

πŸ§ͺ How to Test It

Login to get the token:


bash

Copy

Edit

curl -X POST http://localhost:5000/login -H "Content-Type: application/json" \

-d '{"username": "admin", "password": "password"}'

Access the protected route using the token:


bash

Copy

Edit

curl http://localhost:5000/protected -H "Authorization: Bearer <your_token_here>"

✅ Summary

Step Description

/login route Authenticates and returns a JWT

token_required Decorator that protects your endpoints

/protected A secure route that requires a valid token


πŸ”’ Security Tips

Use HTTPS to protect tokens in transit.


Store secret keys securely (e.g., in environment variables).


Always set an expiration (exp) on tokens.


Use refresh tokens for long-term sessions.

Learn Full Stack Python Course in Hyderabad

Read More

Introduction to Python for Full Stack Developers

Implementing User Authentication in Django

Authentication and Security

Building a Data-Driven Web Application with Python

Visit Our IHUB Talent Training Institute in Hyderabad

Get Directions

Comments

Popular posts from this blog

How to Install and Set Up Selenium in Python (Step-by-Step)

Tosca for API Testing: A Step-by-Step Tutorial

Feeling Stuck in Manual Testing? Here’s Why You Should Learn Automation Testing