CamKode

Implementing JWT Authentication in Flask

Avatar of Kosal Ang

Kosal Ang

Tue Mar 26 2024

Implementing JWT Authentication in Flask

JWT (JSON Web Token) authentication is a widely-used method for securing web applications. In this tutorial, we'll explore how to implement JWT authentication in Flask using the Flask-JWT-Extended extension. By the end, you'll have a secure authentication system allowing users to register, log in, log out, and access protected routes using JWT tokens.

Prerequisites: Ensure you have Python installed on your system, along with basic knowledge of Flask and web development concepts.

Step 1: Install Required Packages:

Begin by installing the necessary packages using pip:

1pip install Flask Flask-JWT-Extended passlib
2

Step 2: Configure Your Flask App:

Initialize your Flask app and configure it to use JWT:

1from flask import Flask
2from flask_jwt_extended import JWTManager
3
4app = Flask(__name__)
5app.config['JWT_SECRET_KEY'] = 'your_secret_key'
6jwt = JWTManager(app)
7

Step 3: User Authentication Endpoints:

Implement endpoints for user registration, login, and logout:

1from flask import request, jsonify
2from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
3from passlib.hash import sha256_crypt
4
5users = {}  # Placeholder for user data (e.g., stored in database)
6blacklisted_tokens = set()
7
8@app.route('/register', methods=['POST'])
9def register():
10    data = request.get_json()
11    username = data.get('username')
12    password = data.get('password')
13    hashed_password = sha256_crypt.hash(password)
14    users[username] = hashed_password
15    return jsonify({'message': 'User registered successfully'}), 201
16
17@app.route('/login', methods=['POST'])
18def login():
19    data = request.get_json()
20    username = data.get('username')
21    password = data.get('password')
22    if username in users and sha256_crypt.verify(password, users[username]):
23        access_token = create_access_token(identity=username)
24        return jsonify({'access_token': access_token}), 200
25    else:
26        return jsonify({'message': 'Invalid username or password'}), 401
27
28@app.route('/logout', methods=['POST'])
29@jwt_required()
30def logout():
31    jti = get_jwt()['jti']  # Get the unique identifier for the JWT token
32    blacklisted_tokens.add(jti)  # Add the token to the blacklist
33    return jsonify({'message': 'User logged out successfully'}), 200
34

Step 4: Secure Endpoints with JWT:

Protect routes that require authentication using the @jwt_required() decorator:

1@app.route('/protected', methods=['GET'])
2@jwt_required()
3def protected():
4    jti = get_jwt()['jti']
5    if jti in blacklisted_tokens:
6        return jsonify({'message': 'Token has been revoked'}), 401
7    else:
8        identity = get_jwt_identity()
9        return jsonify(logged_in_as=identity), 200
10

Step 5: Running Your Flask App:

Finally, run your Flask app:

1if __name__ == '__main__':
2    app.run(debug=True)
3

Step 6: Testing:

Below are the curl commands to test each of the routes for user registration, login, logout, and accessing a protected route with JWT authentication:

1. User Registration:

1curl -X POST -H "Content-Type: application/json" -d '{"username":"your_username", "password":"your_password"}' http://localhost:5000/register
2

2. User Login:

1curl -X POST -H "Content-Type: application/json" -d '{"username":"your_username", "password":"your_password"}' http://localhost:5000/login
2

3. User Logout (Note: Requires a valid JWT token obtained after login):

1curl -X POST -H "Authorization: Bearer your_access_token" http://localhost:5000/logout
2

4. Access Protected Route (Note: Requires a valid JWT token obtained after login):

1curl -X GET -H "Authorization: Bearer your_access_token" http://localhost:5000/protected
2

Replace your_username, your_password, and your_access_token with the actual values obtained during registration and login. Make sure to start your Flask app before running these curl commands.

Conclusion: Congratulations! You have successfully implemented JWT authentication in your Flask application. Users can now register, log in, log out, and access protected routes using JWT tokens. Customize and expand these functionalities as needed for your specific application requirements. Happy coding!

Related Posts

How to Create and Use Virtual Environments

How to Create and Use Virtual Environments

Unlock the full potential of Python development with our comprehensive guide on creating and using virtual environments

Creating a Real-Time Chat Application with Flask and Socket.IO

Creating a Real-Time Chat Application with Flask and Socket.IO

Learn how to enhance your real-time chat application built with Flask and Socket.IO by displaying the Socket ID of the message sender alongside each message. With this feature, you can easily identify the owner of each message in the chat interface, improving user experience and facilitating debugging. Follow this step-by-step tutorial to integrate Socket ID display functionality into your chat application, empowering you with deeper insights into message origins.

How to Perform Asynchronous Programming with asyncio

How to Perform Asynchronous Programming with asyncio

Asynchronous programming with asyncio in Python allows you to write concurrent code that can handle multiple tasks concurrently, making it particularly useful for I/O-bound operations like web scraping

Mastering Data Visualization in Python with Matplotlib

Mastering Data Visualization in Python with Matplotlib

Unlock the full potential of Python for data visualization with Matplotlib. This comprehensive guide covers everything you need to know to create stunning visualizations, from basic plotting to advanced customization techniques.

Building a Secure Web Application with User Authentication Using Flask-Login

Building a Secure Web Application with User Authentication Using Flask-Login

Web authentication is a vital aspect of web development, ensuring that only authorized users can access protected resources. Flask, a lightweight web framework for Python, provides Flask-Login

Simplifying Excel File Handling in Python with Pandas

Simplifying Excel File Handling in Python with Pandas

Learn how to handle Excel files effortlessly in Python using the Pandas library. This comprehensive guide covers reading, writing, and manipulating Excel data with Pandas, empowering you to perform data analysis and reporting tasks efficiently.

Creating a Custom Login Form with CustomTkinter

Creating a Custom Login Form with CustomTkinter

In the realm of Python GUI development, Tkinter stands out as one of the most popular and versatile libraries. Its simplicity and ease of use make it an ideal choice for building graphical user interfaces for various applications.

Building Scalable Microservices Architecture with Python and Flask

Building Scalable Microservices Architecture with Python and Flask

Learn how to build a scalable microservices architecture using Python and Flask. This comprehensive guide covers setting up Flask for microservices, defining API endpoints, implementing communication between services, containerizing with Docker, deployment strategies, and more.

FastAPI: Building High-Performance RESTful APIs with Python

FastAPI: Building High-Performance RESTful APIs with Python

Learn how to leverage FastAPI, a modern web framework for building APIs with Python, to create high-performance and easy-to-maintain RESTful APIs. FastAPI combines speed, simplicity, and automatic documentation generation, making it an ideal choice for developers looking to rapidly develop and deploy APIs.

Beginner's Guide to Web Scraping with BeautifulSoup in Python

Beginner's Guide to Web Scraping with BeautifulSoup in Python

Learn how to scrape websites effortlessly using Python's BeautifulSoup library. This beginner-friendly guide walks you through fetching webpages, parsing HTML content, and extracting valuable data with ease.

© 2024 CamKode. All rights reserved

FacebookTwitterYouTube