Home > Backend Development > Python Tutorial > How to implement JSON Web Token based authentication using Flask-JWT

How to implement JSON Web Token based authentication using Flask-JWT

PHPz
Release: 2023-08-02 16:43:51
Original
1271 people have browsed it

How to implement JSON Web Token based authentication using Flask-JWT

Overview:
In modern web applications, security is crucial. One of the key aspects is authentication. JSON Web Token (JWT) is an open standard for passing claims between web applications. It can verify data integrity through signatures and implement token-based user authentication.

In this article, we will introduce how to use the Flask-JWT extension to implement JSON Web Token-based authentication to protect our Flask application.

Install Flask-JWT:
First, make sure you have installed Flask and Flask-JWT. They can be installed using the following command:

pip install flask
pip install flask-jwt
Copy after login

How to use:
Flask-JWT provides decorators to easily add token validation to Flask routing functions. Here is a simple example:

from flask import Flask
from flask_jwt import JWT, jwt_required, current_identity
from werkzeug.security import safe_str_cmp

app = Flask(__name__)
app.config['SECRET_KEY'] = 'super-secret-key'

class User:
    def __init__(self, id, username, password):
        self.id = id
        self.username = username
        self.password = password

    def __str__(self):
        return f'User(id={self.id}, username={self.username})'

users = [
    User(1, 'admin', 'adminpassword'),
]

def authenticate(username, password):
    user = next((user for user in users if user.username == username), None)
    if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
        return user

def identity(payload):
    user_id = payload['identity']
    return next((user for user in users if user.id == user_id), None)

jwt = JWT(app, authenticate, identity)

@app.route('/protected')
@jwt_required()
def protected():
    return f'Hello, {current_identity}! This route is protected.'

if __name__ == '__main__':
    app.run()
Copy after login

In the above example code, we first imported the required modules. Then, we define a User class to represent the user entity. Next, we define a list of users (assuming a database) to use for authentication.

authenticate function is used to authenticate a user based on the provided username and password. The identity function obtains the user object based on the user ID in the JWT payload.

Then, we initialized a Flask application and set a secret key (SECRET_KEY). We then initialized a jwt object using the JWT class and passed the authenticate and identity functions to it.

The @jwt_required() decorator is used on the /protected route to protect the route. Only authenticated users can access it.

Finally, we launch the Flask application.

Authenticate:
To authenticate, we need to make an HTTP POST request to the application, passing the username and password. Flask-JWT will generate a JWT token for us.

Here is the sample code of how to authenticate:

import requests

def authenticate(username, password):
    response = requests.post('http://localhost:5000/auth', json={'username': username, 'password': password})
    if response.status_code == 200:
        return response.json()['access_token']

access_token = authenticate('admin', 'adminpassword')
print(f'Access Token: {access_token}')
Copy after login

In the above example, we sent an HTTP POST request to the /auth route, passing the user JSON data of name and password. If the authentication is successful, we will get an access_token.

The protected route will accept the token and authenticate the user. Here is an example of how to pass the token in the request header:

import requests

headers = {
    'Authorization': f'Bearer {access_token}'
}

response = requests.get('http://localhost:5000/protected', headers=headers)
print(response.text)
Copy after login

In the above example, we add the token to the Authorization field of the request header and pass it to /protectedRouting. If the token is valid, we will get a response from the protected route.

Summary:
In this article, we learned how to use the Flask-JWT extension to implement JSON Web Token-based authentication. We learned how to add an authentication decorator in a Flask application and demonstrated how to authenticate with sample code. JSON Web Token provides a simple and secure authentication mechanism that can be applied to a variety of web applications.

The above is the detailed content of How to implement JSON Web Token based authentication using Flask-JWT. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template