Introduction
API authentication is crucial for securing your Flask-based web services. Token-based authentication is a popular method that involves issuing tokens to users for accessing protected resources. In this guide, we'll explore how to implement token-based authentication in Flask, including creating, issuing, and verifying tokens.
Step 1: Setting Up Your Flask Application
Start by setting up your Flask application. Create a virtual environment and install Flask. Here's a sample directory structure:
my-api-app/
app.py
Step 2: Generating Tokens
Create a token generation mechanism in your Flask app. You can use libraries like PyJWT (Python JSON Web Tokens) for this. Here's a simplified example:
# app.py
from flask import Flask, request, jsonify
import jwt
app = Flask(__name)
app.config['SECRET_KEY'] = 'your_secret_key'
@app.route('/get_token', methods=['POST'])
def get_token():
data = request.get_json()
if 'username' in data and 'password' in data:
token = jwt.encode({'user': data['username']}, app.config['SECRET_KEY'], algorithm='HS256')
return jsonify({'token': token})
return jsonify({'message': 'Invalid credentials'}), 401
if __name__ == '__main__':
app.run(debug=True)
Step 3: Authenticating Requests
Protect your API endpoints by verifying tokens in incoming requests. Use Flask decorators to authenticate routes. Here's an example:
# app.py
from functools import wraps
import jwt
# ... (Previous code)
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.headers.get('Authorization')
if not token:
return jsonify({'message': 'Token is missing'}), 401
try:
data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])
except jwt.ExpiredSignatureError:
return jsonify({'message': 'Token has expired'}), 401
except jwt.InvalidTokenError:
return jsonify({'message': 'Invalid token'}), 401
return f(*args, **kwargs)
return decorated
@app.route('/protected_resource', methods=['GET'])
@token_required
def protected_resource():
return jsonify({'message': 'This is a protected resource'})
if __name__ == '__main__':
app.run(debug=True)
Step 4: Requesting a Token
Clients must request a token by sending their credentials to the server. Here's an example of how to request a token using the `requests` library in Python:
import requests
url = 'http://localhost:5000/get_token'
data = {'username': 'your_username', 'password': 'your_password'}
response = requests.post(url, json=data)
if response.status_code == 200:
token = response.json()['token']
print(f'Token: {token}')
else:
print('Authentication failed')
Conclusion
Token-based authentication is a powerful method for securing your Flask APIs. By following these steps and best practices, you can implement secure and straightforward API authentication. Keep your secret key safe and use tokens to protect your resources effectively.