小编ano*_*bit的帖子

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

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

我已将 Django 配置为将令牌身份验证与 djangorestframework-simplejwt 结合使用。

# 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',
    ],
Run Code Online (Sandbox Code Playgroud)

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

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

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

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 …
Run Code Online (Sandbox Code Playgroud)

python django django-rest-framework django-rest-framework-jwt django-rest-framework-simplejwt

6
推荐指数
1
解决办法
6188
查看次数