Django:身份验证凭据未提供错误,因为访问和刷新令牌设置为没有授权标头的 HttpOnly cookie

问题描述

我已将 SimpleJWT accessrefresh 令牌设置为 HttpOnly cookie。因此,我认为我不再需要使用“授权”标头,因此将其删除。现在,当我提出请求时,它会显示

{"detail": "Authentication credentials were not provided."}

在这里,我想我需要在视图中将 Authorization 标头设置为 access 标记。到目前为止,我已经编写了这段代码,但它不起作用。我希望它将 Authorization 标头设置为请求并继续:

def list(self,request):
    access = request.COOKIES.get('access')
    request.Meta['Authorization'] = f"Bearer {access}"
    print(request.Meta.get('Authorization'))
    serializer = self.serializer_class(instance = self.request.user) 
    return Response(serializer.data)

如果请求不是来自客户端,我如何发送带有请求的 Authorization 标头?

解决方法

像这样定义您的自定义 JWT 身份验证视图:

from rest_framework_simplejwt.authentication import JWTAuthentication
from django.conf import settings


class CustomAuthentication(JWTAuthentication):
    
    def authenticate(self,request):
        header = self.get_header(request)
        
        if header is None:
            raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE']) or None
        else:
            raw_token = self.get_raw_token(header)
        if raw_token is None:
            return None

        validated_token = self.get_validated_token(raw_token)

        return self.get_user(validated_token),validated_token

这里给出自定义 JWT Token 的路径:

settings.py:

SIMPLE_JWT = {
........
'AUTH_COOKIE': 'access_token',}
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'authentication.authenticate.CustomAuthentication',),}