python - 如何使用从登录视图中获得的 jwt 令牌进行身份验证
问题描述
我需要创建 JWT 令牌身份验证,但我不知道如何,您能解释一下如何做得更好或举一些例子吗?
我的观点:
class UserLogin(generics.CreateAPIView):
"""
POST auth/login/
"""
# This permission class will overide the global permission
# class setting
permission_classes = (permissions.AllowAny,)
queryset = User.objects.all()
serializer_class = TokenSerializer
def post(self, request, *args, **kwargs):
username = request.data.get("username", "")
password = request.data.get("password", "")
user = auth.authenticate(request, username=username, password=password)
if user is not None:
auth.login(request, user)
return Response({
"token": jwt_encode_handler(jwt_payload_handler(user)),
'username': username,
}, status=200)
return Response(status=status.HTTP_401_UNAUTHORIZED)
解决方案
您正在该视图中创建令牌。之后,您需要另外两个机制:
您的客户端应在每个请求的授权标头中将此令牌发送给 API ,例如:
Authorization: Bearer your_token
- 在 api 方面,您需要使用身份验证类,该类查找 Authorization 标头,获取令牌并对其进行解码,如果令牌有效,则找到与令牌关联的用户实例。
如果您使用一个用于 drf jwt 身份验证的库,它应该有一个您可以使用的身份验证类。如果您手动实现它,您需要自己编写一个继承 DRF 的BaseAuthentication类的身份验证类。它基本上看起来像这样:
class JwtAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
auth_header = request.META.get('HTTP_AUTHORIZATION')
if auth_header:
key, token = auth_header.split(' ')
if key == 'Bearer':
# Decode the token here. If it is valid, get the user instance associated with it and return it
...
return user, None
# If token exists but it is invalid, raise AuthenticationFailed exception
# If token does not exist, return None so that another authentication class can handle authentication
您需要告诉 DRF 使用此身份验证类。为此将其添加到您的设置文件中:
REST_FRAMEWORK = {
...
'DEFAULT_AUTHENTICATION_CLASSES': [
'path.to.JwtAuthentication',
...
]
}
推荐阅读
- javascript - 如何根据当前状态值使单选按钮选中/激活
- flutter - 重构问题:提取为小部件/方法/变量......有什么优点和缺点?
- python - Telegram-python-Bot 使用 callback_query 获取用户文本输入
- xamarin - 将 CarouselPage 转换为 CarouselView
- mongodb - Mongo db 4.2:将数组项的字段替换为匹配文档的另一个字段的值
- r - 在带有 tidymodels 的 r 中:警告消息:“所有模型在 [fit_resamples()] 中均失败。请参阅 `.notes` 列。” 内部:错误:在指标中:`roc_auc`
- c++ - 是否可以在 void 函数中使用 getline ?
- meteor - Meteortesting mocha 代码覆盖率错误:无法保存 json / html 报告
- java - 没有为 JDateChooser(string,string,char) 找到合适的构造函数
- java - 排序在本地工作但不在 kubernetes 上的文件