jwt authentication python flask
To implement JWT authentication in a Flask application using Python, you can follow these steps:
- Import the required modules:
from flask import Flask, request
from flask_jwt_extended import JWTManager, jwt_required, create_access_token
- Here, we import the Flask module for creating the application and handling HTTP requests.
We also import the JWTManager module from the flask_jwt_extended package, which provides JWT authentication functionality.
Create the Flask application:
app = Flask(__name__)
This creates a Flask application object.
Configure the JWT secret key:
app.config['JWT_SECRET_KEY'] = 'your-secret-key'
The JWT secret key is used to encrypt and decrypt the JWT tokens. Replace
'your-secret-key'
with your own secret key.Initialize the JWTManager:
jwt = JWTManager(app)
This initializes the JWTManager with the Flask application object.
Define a route for user login:
@app.route('/login', methods=['POST'])
def login():
username = request.json.get('username', None)
password = request.json.get('password', None)
# Validate the username and password (you can use your own logic here)
if username != 'admin' or password != 'password':
return {'message': 'Invalid credentials'}, 401
# Generate an access token
access_token = create_access_token(identity=username)
# Return the access token
return {'access_token': access_token}, 200
- This route handles the user login functionality.
- It expects a POST request with a JSON payload containing the username and password.
- You can add your own validation logic for the username and password.
- If the credentials are valid, it generates an access token using the
create_access_token
function from the flask_jwt_extended module. The access token is returned as a JSON response.
Protect a route with JWT authentication:
@app.route('/protected', methods=['GET'])
@jwt_required()
def protected():
# Access token is valid, perform protected actions
return {'message': 'This is a protected route'}, 200
- This route is protected with JWT authentication using the
@jwt_required()
decorator. Only requests that include a valid access token in the Authorization header will be allowed to access this route.
Run the application:
if __name__ == '__main__':
app.run()
- This runs the Flask application.
Make sure to install the necessary dependencies by running pip install Flask flask_jwt_extended
.
These steps outline how to implement JWT authentication in a Flask application using Python. By following these steps, you can add secure authentication to your application by leveraging JWT tokens.