gpt4 book ai didi

python - 使用 JWT token 对 Django Rest Framework 中的 POST 请求进行未经授权的响应

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:59 27 4
gpt4 key购买 nike

我正在使用 Django Rest Framework 构建 REST API。我目前遇到一个问题,我的一些端点返回 HTTP 401 Unauthorized,而我的绝大多数端点返回正确的响应。为了进行身份验证,我将 JWT token 与 djangorestframework-simplejwt 一起使用。

我已将 Django 配置为通过 djangorestframework-simplejwt 使用 token 身份验证。

# rest framework config settings
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
# 'rest_framework.permissions.AllowAny',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
'rest_framework_simplejwt.authentication.JWTAuthentication',
],

当我在请求中传递有效的访问 token 时,我的绝大多数端点都会返回有效数据。如果我没有发送有效 token ,我会收到 HTTP 403。

另一方面,我有一些自定义 API View ,无论我是否传递有效 token ,它们都会返回 HTTP 401。

我已将代码包含在下面我的一个有问题的 View 中。

class CheckDifferentialView(generics.GenericAPIView):
permission_classes = [IsAuthenticated]
authentication_classes = [TokenAuthentication]
serializer_class = QuizDifferentialSerializer

def post(self, request, *args, **kwargs):
"""
A function to check a quiz question and to update a user's record of questions answered
"""
print(request.META)
if 'answer' not in request.data:
return JsonResponse({'Error': 'answer not found in request'}, status=status.HTTP_400_BAD_REQUEST)

answer = get_object_or_404(Differential, pk=request.data['answer'])
serializer = QuizDifferentialSerializer(answer)

if answer.is_correct:
pass
# record correct results
else:
pass
# record failed result

return Response(serializer.data, status=status.HTTP_200_OK)

这是我用来测试 API 的脚本

import requests
import json

POST_LOGIN_URL = 'http://localhost:8000/api/v1/token/'
POST_URL= 'http://localhost:8000/api/v1/check_differential'
REQUEST_URL = 'http://localhost:8000/api/v1/users'

with requests.Session() as session:
post = session.post(POST_LOGIN_URL, json={"username": "j", "monkey": "aphextwin21"})
token = json.loads(post.text)['access']
headers = {'Authorization': 'Bearer ' + token}

r = session.post(POST_URL, headers=headers, json={"answer": "2"})
# r = session.get(REQUEST_URL, headers=headers)
print(token)

print(r.text, r.status_code)

所需的行为是,如果我向该端点发送一个带有有效 token 的 POST 请求,该端点将授权我并继续其工作。如果没有提供带有有效访问 token 的授权 header ,那么我希望它会拒绝该请求。


更新


热情的Martin亲切地指出

authentication_classes = [TokenAuthentication]

正在覆盖我的设置文件中的默认值。我不知道就 Django 而言,TokenAuthentication 和 JWTAuthentication 的处理方式不同。现在我知道了。

从我的 View 中删除 authentication_classess = [TokenAuthentication] 后, View 正常工作。

最佳答案

View 的身份验证类仅显式设置为 TokenAuthentication。它不适用于 JWT token 。

 authentication_classes = [TokenAuthentication]

您要么删除它让默认类处理它,要么将其更改为接受 JWTAuthentication

关于python - 使用 JWT token 对 Django Rest Framework 中的 POST 请求进行未经授权的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58448531/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com