Flask API Authentication with OAuth 2.0 and JWT
Securing APIs is one of the most critical aspects of backend development. In modern applications, OAuth 2.0 combined with JWT (JSON Web Tokens) has become a standard for implementing secure and scalable authentication. When building APIs using Flask, integrating OAuth 2.0 and JWT ensures that only authorized clients can access protected resources. In this blog, we’ll explore how to implement API authentication in a Flask app using OAuth 2.0 and JWT.
What is OAuth 2.0?
OAuth 2.0 is an authorization framework that allows third-party applications to access a user's data without exposing their credentials. It involves issuing access tokens to clients after successful authentication, typically via an identity provider (like Google, GitHub, or a custom auth server).
What is JWT?
JWT (JSON Web Token) is a compact and self-contained method for securely transmitting information between parties as a JSON object. In OAuth 2.0, access tokens are often issued in the form of JWTs.
A JWT has three parts:
Header – Contains the token type and signing algorithm.
Payload – Contains claims (user ID, roles, expiry).
Signature – Ensures token integrity and authenticity.
Implementing OAuth 2.0 + JWT in Flask
Step 1: Setup Flask and Dependencies
bash
pip install Flask PyJWT Flask-Cors requests
python
Copy
Edit
from flask import Flask, request, jsonify
import jwt
import datetime
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key' # Should be kept safe and complex
Step 2: Mock OAuth 2.0 Flow (for learning)
In a real scenario, you'd redirect the user to an external identity provider. For simplicity, let’s simulate this with a login endpoint.
python
Copy
Edit
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data.get('username')
password = data.get('password')
# Simulate user verification
if username == 'admin' and password == 'password':
token = jwt.encode({
'user': username,
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)
}, app.config['SECRET_KEY'], algorithm='HS256')
return jsonify({'access_token': token})
return jsonify({'message': 'Invalid credentials'}), 401
Step 3: Create a Protected Endpoint
This endpoint requires a valid JWT to access:
python
Copy
Edit
from functools import wraps
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = None
if 'Authorization' in request.headers:
token = request.headers['Authorization'].split()[1]
if not token:
return jsonify({'message': 'Token is missing'}), 401
try:
data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])
current_user = data['user']
except jwt.ExpiredSignatureError:
return jsonify({'message': 'Token has expired'}), 401
except jwt.InvalidTokenError:
return jsonify({'message': 'Invalid token'}), 403
return f(current_user, *args, **kwargs)
return decorated
@app.route('/protected', methods=['GET'])
@token_required
def protected_route(current_user):
return jsonify({'message': f'Welcome, {current_user}! This is protected data.'})
Step 4: Test Your API
Login with valid credentials to get the token.
Use the token in the Authorization header:
Authorization: Bearer <token>
You can test this flow using Postman or cURL.
Conclusion
Using OAuth 2.0 for authentication and JWT for token-based access control is a secure and scalable way to protect your Flask APIs. While this tutorial uses a simplified mock of OAuth, the same JWT-based validation logic applies when integrating with real OAuth providers. With proper implementation, this approach ensures that only authorized users can access protected resources—keeping your application secure and user data safe.
Learn FullStack Python Training Course
Read More : Fullstack Flask: Handling File Uploads and Downloads via APIs
Read More : Building CRUD APIs with Flask and SQLAlchemy
Read More : Flask and OpenAPI: Designing APIs with Swagger for Fullstack Applications
Visit Quality Thought Training Institute
Comments
Post a Comment