当我使用授权发送标头时,django 中出现“给定令牌对任何令牌类型都无效”错误:无

问题描述 投票:0回答:1

当我向后端发送请求时,出现错误:

{
    "detail": "Given token not valid for any token type",
    "code": "token_not_valid",
    "messages": [
        {
            "token_class": "AccessToken",
            "token_type": "access",
            "message": "Token is invalid or expired"
        }
    ]
}

我在views.py中有这个

class ProblemViewSet(viewsets.ModelViewSet):
    queryset = models.Problem.objects.all()
    serializer_class = serializers.ProblemSerializer
    permission_classes = []

    def retrieve(self, request, *args, **kwargs):
        print(request.META)
        instance = self.get_object()
        user = request.user

        if user is not None and not user.is_anonymous:
            interaction, created = models.InteractionUserProblem.objects.get_or_create(user=user, problem=instance)

            if created:
                interaction.is_viewed = True
                interaction.save()

        serializer = self.get_serializer(instance)
        return Response(serializer.data)

这在settings.py中

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': ["rest_framework_simplejwt.authentication.JWTAuthentication"],
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
    "TEST_REQUEST_DEFAULT_FORMAT": "json",
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10,
}

如果用户未经过身份验证,前端会出现带有 Authorization: Bearer none 的标头。 我知道添加

authentication_classes = []
的解决方案,但我需要身份验证,以便在用户经过身份验证时识别用户。那么我该如何解决这个问题,也许我需要添加一些中间件?

我尝试添加

authentication_classes = []
,但这对我来说不是解决方案。我需要以某种方式捕获 Authorization: Bearer none 并处理它。

python django django-rest-framework jwt
1个回答
0
投票

不要向未经身份验证的用户发送授权标头。
如果你必须发送它,不要使用

Authorization: "Bearer none"
,只使用
Authorization: "none"
或其他任何东西(我的意思是不以
Bearer
开头),这样后端将忽略这个标头并且不会导致错误。

我还建议保护您的视图免受未经授权的用户的攻击,如下所示:

from rest_framework.permissions import IsAuthenticated

class ProblemViewSet(viewsets.ModelViewSet):
    permission_classes = [IsAuthenticated]
© www.soinside.com 2019 - 2024. All rights reserved.