Flask API Authentication with OAuth 2.0 and JWT
In modern web development, securing APIs is a critical part of the architecture. When building APIs with Flask, implementing robust authentication is essential to prevent unauthorized access and protect user data. One of the most effective and widely used strategies is combining OAuth 2.0 with JSON Web Tokens (JWT). This blog will guide you through the basic concept and implementation of OAuth 2.0 and JWT for securing a Flask API.
🔐 What is OAuth 2.0?
OAuth 2.0 is an open standard for access delegation commonly used as a way to grant websites or applications limited access to user information without exposing credentials. It allows a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner or by allowing the third-party application to obtain access on its own behalf.
For example, logging in with Google or GitHub uses OAuth 2.0 behind the scenes.
🔒 What is JWT?
JSON Web Tokens (JWT) are a compact and self-contained way of securely transmitting information between parties as a JSON object. The token is digitally signed using a secret key (HMAC) or a public/private key pair (RSA or ECDSA).
A JWT typically consists of three parts:
- Header – Contains the type of token and algorithm used.
- Payload – Contains the claims (user data).
- Signature – Verifies the sender and ensures the message wasn’t changed.
🔧 Implementing OAuth 2.0 + JWT in Flask
Here’s how you can use OAuth 2.0 for authentication and then issue a JWT for protected API access.
1. Set Up Flask and Required Libraries
Install the necessary libraries:
bash
pip install Flask flask-oauthlib PyJWT
Import them in your app:
python
from flask import Flask, request, jsonify
import jwt
import datetime
2. User Logs In via OAuth Provider
Use flask-dance or Authlib to integrate with an OAuth provider like Google. Once the OAuth flow is complete, you'll get an access token and user info.
Example with Google OAuth (using Authlib):
python
from authlib.integrations.flask_client import OAuth
oauth = OAuth(app)
google = oauth.register(
name='google',
...
)
Once the user logs in and your app receives the user profile, you can generate a JWT token for session management.
3. Generate JWT After Successful Login
python
@app.route('/login/callback')
def callback():
user_info = get_user_info_somehow()
token = jwt.encode({
'user_id': user_info['id'],
'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)
}, 'SECRET_KEY', algorithm='HS256')
return jsonify({'token': token})
4. Protect Your Flask Routes with JWT
Use a decorator to validate the token:
python
from functools import wraps
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.headers.get('Authorization')
if not token:
return jsonify({'message': 'Token is missing!'}), 403
try:
data = jwt.decode(token.split(" ")[1], 'SECRET_KEY', algorithms=['HS256'])
except:
return jsonify({'message': 'Token is invalid or expired!'}), 403
return f(*args, **kwargs)
return decorated
Use it on your route:
python
@app.route('/dashboard')
@token_required
def dashboard():
return jsonify({'message': 'Welcome to the secure dashboard!'})
✅ Conclusion
Combining OAuth 2.0 and JWT provides a powerful authentication and authorization mechanism for Flask APIs. OAuth 2.0 handles the identity verification via a trusted third-party provider, while JWT allows your backend to manage secure sessions without maintaining server-side state.
With this setup, your Flask API is much more secure, scalable, and ready for integration with modern front-end applications and microservices.
Learn FullStack Python Training
Read More : Flask REST API Documentation with Flask-RESTPlus
Visit Our IHUB Talent Training Institute in Hyderabad
Get Direction
Comments
Post a Comment