Implementing JWT Authentication with Flask and Django
In modern web development, securing APIs and user sessions is essential. JWT (JSON Web Tokens) has emerged as a popular method for handling stateless authentication in RESTful applications. This blog will walk you through how to implement JWT authentication in both Flask and Django, two leading Python web frameworks.
What is JWT?
JWT stands for JSON Web Token, a compact, URL-safe way of representing claims between two parties. It typically consists of three parts: header, payload, and signature. JWTs are self-contained, meaning they carry user information and authentication claims, allowing the server to verify identity without storing session data.
Implementing JWT in Flask
Step 1: Install Required Packages
pip install Flask Flask-JWT-Extended
Step 2: Basic Setup
from flask import Flask, jsonify, request
from flask_jwt_extended import JWTManager, create_access_token, jwt_required
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'your-secret-key'
jwt = JWTManager(app)
Step 3: Create Login and Protected Routes
@app.route('/login', methods=['POST'])
def login():
username = request.json.get('username')
password = request.json.get('password')
if username == 'admin' and password == 'admin':
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token), 200
return jsonify(msg='Invalid credentials'), 401
@app.route('/protected', methods=['GET'])
@jwt_required()
def protected():
return jsonify(msg='Access granted'), 200
Implementing JWT in Django (Using Django REST Framework)
Step 1: Install Required Packages
pip install djangorestframework djangorestframework-simplejwt
Step 2: Update Settings
In settings.py, add:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
Step 3: Create Token Views
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
urlpatterns = [
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]
Step 4: Secure Your Views
Use Django REST Framework’s @permission_classes to protect endpoints:
from rest_framework.permissions import IsAuthenticated
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def protected_view(request):
return Response({"message": "Authenticated"})
Conclusion
JWT makes user authentication secure and scalable, especially in stateless applications. Whether you're using Flask for lightweight APIs or Django for full-featured web apps, integrating JWT is straightforward with the right libraries. By adopting JWT, developers can ensure secure data exchange and improve API performance.
Learn Fullstack Python Training in Hyderabad
Read More:
Creating Dynamic Frontend Interfaces with React and Python Backend
Using Vue.js with a Python Backend
Deploying Fullstack Python Applications on AWS
Containerizing Fullstack Python Apps with Docker
Visit our IHub Talent Training Institute
Comments
Post a Comment