django-rest-framework - Django Rest 框架 JWT 身份验证
问题描述
我在 JWT 登录后发布/获取任何请求时遇到问题。(我正在使用djangorestframework-jwt库)用户成功登录,应用程序返回 json 令牌,但是当我将此令牌用于下一个请求时,我得到
{
"detail": "Authentication credentials were not provided."
}
设置.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
JWT_AUTH = {
'JWT_ALLOW_REFRESH': True,
'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1),
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
}
登录视图
def post(self, request, format=None):
if not request.data:
return Response({'Error': "Please provide username/password"}, status=status.HTTP_400_BAD_REQUEST)
username = request.data['username']
password = request.data['password']
try:
user = User.objects.get(email=username, password=password)
except User.DoesNotExist:
return Response({'Error': "Invalid username/password"}, status=status.HTTP_400_BAD_REQUEST)
if user:
payload = {
'id': user.id,
'email': user.email,
'first_name': user.first_name
}
jwt_token = jwt.encode(payload, "SECRET_KEY") # to be changed
return Response({'token': jwt_token}, status=status.HTTP_200_OK)
然后每个其他视图都包含
authentication_class = (JSONWebTokenAuthentication,)
permission_classes = (IsAuthenticated,)
我已经用邮递员和 curl 进行了测试,但我得到了同样的错误。不确定标题格式是否有错误,或者我是否缺少其他东西。任何帮助将不胜感激!
编辑:我已将设置更改为
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
但现在我明白了
{
"detail": "Error decoding signature."
}
编辑:我认为问题在于jwt_token = jwt.encode(payload, 'SECRET_KEY')
可能会返回一个无法识别的令牌......如果我使用生成的令牌,obtain_jwt_token
那么我可以查询任何端点。谁能解释一下?
编辑:所以我更改为jwt_token = jwt_encode_handler(payload)
并且设置文件包含JWT_SECRET_KEY
(当我验证登录 jwt 后收到的令牌时,它确实是具有正确有效负载和秘密的正确令牌)但它仍然无法识别"detail": "Invalid signature."
解决方案
我设法解决了我的问题。在对用户进行身份验证时,我正在检查user
我之前创建的自定义表,该表与 django 的auth_user
表不同。我更改了 django 的设置以使用我的自定义用户表,然后使用来自身份验证的令牌也适用于其他请求。
AUTH_USER_MODEL = 'main.User'
推荐阅读
- java - 具有多个模块的 Maven 项目中 Docker 容器的集成测试
- android - 如何从 1st spinner android kotlin 中使用的 2nd spinner 中删除项目
- python - 使用 pandas 将 json 转换为 csv
- visual-studio - 列出所有实际使用的引用
- graphql - 解决 graphql 查询中的联合结果时出现意外的 *Missing Field* 错误(Vue Apollo 客户端)
- rust - 如何将一组跟踪订阅者合二为一?
- c - break vs goto:在 C 中的以下 bool 函数中哪个更合适?
- r - split 在 sink() 函数中究竟做了什么?
- javascript - 有条件地将具有相同键但不同值的对象推送到数组以避免键入
- c# - 重新排序通用 BindingList 的元素