通过ngrok连接时未设置Cookie

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

我正在尝试对我的Django应用程序使用会话身份验证。当我使用本地主机地址将前端应用程序连接到本地运行的后端服务器时,浏览器将设置在Set-Cookie标头(包括session_id和csrf_token)中发送的cookie,并且用户可以进行身份​​验证。但是,当我使用指向同一台服务器的ngrok URL时,浏览器未设置session_id和csrf_token cookie,并且该用户Forbidden(403 http response)无法访问受保护的端点。

Some more context:我在前端使用axios。在后端使用DRF的django。我正在尝试使用DRF的SessionAuthentication进行身份验证

Django设置文件

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES' : [
        'rest_framework.authentication.SessionAuthentication',
        'knox.auth.TokenAuthentication',
    ]
}

认证端点

class ProfileAPI(views.APIView):
    serializer_class = ProfileSerializer
    permission_classes = [IsAuthenticated & UserorAdminAccessOnly]

    def get(self, request):
        user = getCorrespondingUser(request)
        profile = Profile.objects.get(user=user)
        serializer = EmergencyFundSerializer(profile)
        self.check_object_permissions(self.request, profile)
        return Response(serializer.data)
authentication django-rest-framework axios session-cookies ngrok
1个回答
0
投票

解决方法是通过将django发送的默认SameSite cookie值添加到设置文件中来更改它:

SESSION_COOKIE_SAMESITE = None
CSRF_COOKIE_SAMESITE = None

对于无法识别这些设置的django版本,请安装django-rest-swagger,然后重试。

© www.soinside.com 2019 - 2024. All rights reserved.