【问题标题】:Cookies not set when connected through ngrok通过 ngrok 连接时未设置 Cookie
【发布时间】:2020-03-14 17:50:54
【问题描述】:

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

更多上下文:我在前端使用 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】:

    修复方法是更改​​ django 发送的默认 SameSite cookie 值,方法是将其添加到设置文件中:

    SESSION_COOKIE_SAMESITE = None
    CSRF_COOKIE_SAMESITE = None
    

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

    【讨论】:

      猜你喜欢
      • 2016-09-18
      • 2012-07-21
      • 2019-03-04
      • 2011-08-25
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多