Camkode
Camkode

Implementing JWT Authentication in Flask

Posted by Kosal

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:

pip install Flask Flask-JWT-Extended passlib

Step 2: Configure Your Flask App:

Initialize your Flask app and configure it to use JWT:

from flask import Flask
from flask_jwt_extended import JWTManager

app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'your_secret_key'
jwt = JWTManager(app)

Step 3: User Authentication Endpoints:

Implement endpoints for user registration, login, and logout:

from flask import request, jsonify
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from passlib.hash import sha256_crypt

users = {}  # Placeholder for user data (e.g., stored in database)
blacklisted_tokens = set()

@app.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    hashed_password = sha256_crypt.hash(password)
    users[username] = hashed_password
    return jsonify({'message': 'User registered successfully'}), 201

@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    if username in users and sha256_crypt.verify(password, users[username]):
        access_token = create_access_token(identity=username)
        return jsonify({'access_token': access_token}), 200
    else:
        return jsonify({'message': 'Invalid username or password'}), 401

@app.route('/logout', methods=['POST'])
@jwt_required()
def logout():
    jti = get_jwt()['jti']  # Get the unique identifier for the JWT token
    blacklisted_tokens.add(jti)  # Add the token to the blacklist
    return jsonify({'message': 'User logged out successfully'}), 200

Step 4: Secure Endpoints with JWT:

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

@app.route('/protected', methods=['GET'])
@jwt_required()
def protected():
    jti = get_jwt()['jti']
    if jti in blacklisted_tokens:
        return jsonify({'message': 'Token has been revoked'}), 401
    else:
        identity = get_jwt_identity()
        return jsonify(logged_in_as=identity), 200

Step 5: Running Your Flask App:

Finally, run your Flask app:

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

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:

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

2. User Login:

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

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

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

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

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

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!