Django JWT 实现指南:使用 django-rest-framework-simplejwt
Django 可以使用第三方库来实现 JWT,如 'django-rest-framework-simplejwt' 和 'djangorestframework-jwt' 等。
下面以 'django-rest-framework-simplejwt' 为例,介绍如何在 Django 中实现 JWT:
- 安装 'django-rest-framework-simplejwt':
pip install djangorestframework-simplejwt
- 在项目的 'settings.py' 中添加以下配置:
INSTALLED_APPS = [
# ...
'rest_framework',
'rest_framework_simplejwt',
# ...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
}
- 在视图中使用 JWT:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.authentication import JWTAuthentication
class LoginView(APIView):
def post(self, request):
# 验证用户名和密码,获取用户信息
# ...
# 生成 JWT token
refresh = RefreshToken.for_user(user)
access_token = str(refresh.access_token)
return Response({'access_token': access_token})
class ProtectedView(APIView):
authentication_classes = [JWTAuthentication]
def get(self, request):
# 通过 JWT token 验证用户身份
# ...
return Response({'message': 'You are authorized'})
在 'LoginView' 中,验证用户名和密码,获取用户信息后,使用 'RefreshToken' 生成 JWT token(包括 access token 和 refresh token),并将 access token 返回给客户端。
在 'ProtectedView' 中,使用 'JWTAuthentication' 进行身份验证,只有携带有效的 JWT token 才能访问该视图。
以上是一个简单的 JWT 实现示例,具体的实现方式可以根据实际需求进行调整。
原文地址: https://www.cveoy.top/t/topic/n8b8 著作权归作者所有。请勿转载和采集!