Using JWT Authentication in Full Stack Python Apps

 WT (JSON Web Token) authentication is a popular way to manage secure user sessions in full-stack Python apps. It’s stateless, scalable, and works well for APIs. Here’s a breakdown of how to implement JWT authentication in a full-stack Python app.


πŸ” What is JWT?

JWT is a compact, URL-safe token that contains claims (user data) and is digitally signed. It typically includes:

  • Header: Algorithm and token type

  • Payload: Claims (e.g., user id, roles)

  • Signature: Verifies that the token hasn't been tampered with


πŸ—️ Tech Stack Example

Let’s say your full-stack app uses:

  • Backend: Python with Flask (or FastAPI)

  • Frontend: React (or any JS framework)

  • Database: PostgreSQL or MongoDB


🧠 How JWT Auth Works in Full Stack

  1. User logs in → Frontend sends login data to backend

  2. Backend validates credentials → Creates and sends JWT back

  3. Frontend stores JWT → Typically in localStorage or sessionStorage

  4. Frontend includes JWT in requests → Usually in Authorization: Bearer <token>

  5. Backend verifies token → Allows or denies access


πŸ› ️ Backend: Python (Flask Example)

Install Dependencies:

bash
pip install Flask PyJWT Flask-CORS

Sample Flask Code:

python
from flask import Flask, request, jsonify import jwt import datetime from functools import wraps app = Flask(__name__) app.config['SECRET_KEY'] = 'your_secret_key' # Decorator for protecting routes def token_required(f): @wraps(f) def decorated(*args, **kwargs): token = request.headers.get('Authorization', None) if token: try: token = token.split(" ")[1] # Remove 'Bearer' data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"]) current_user = data['user'] except: return jsonify({'message': 'Invalid Token'}), 401 else: return jsonify({'message': 'Token Missing'}), 403 return f(current_user, *args, **kwargs) return decorated # Login route @app.route('/login', methods=['POST']) def login(): auth_data = request.json if auth_data['username'] == 'admin' and auth_data['password'] == 'password': token = jwt.encode({ 'user': auth_data['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 # Protected route @app.route('/protected', methods=['GET']) @token_required def protected(current_user): return jsonify({'message': f'Welcome {current_user}'}) if __name__ == '__main__': app.run(debug=True)

🌐 Frontend (React Example)

javascript
// Store the token after login localStorage.setItem('token', response.data.token); // Send with request fetch('/protected', { headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') } }) .then(res => res.json()) .then(data => console.log(data));

🧩 Tips

  • Use HTTPS to protect tokens in transit

  • Set token expiration (exp) and refresh it with refresh tokens

  • Don’t store tokens in localStorage if XSS is a concern (use HttpOnly cookies instead)

  • Use libraries like Flask-JWT-Extended or FastAPI for better handling


πŸ§ͺ Want a full project example?

Let me know if you'd like a working GitHub project template or a walkthrough using FastAPI + React or Flask + Vue.

READ MORE

GET DIRECTIONS

Comments

Popular posts from this blog

Integrating WebSockets with React and Python Backend

How to Repurpose Old Content for Better Engagement

Introduction to AWS for Data Science Beginners