csrf_exempt 设置但 CSRF 失败:Referer 检查失败 - 无 Referer

Kim*_*mor 6 django csrf google-cloud-endpoints

我有一个后端 API,它位于 django 中并部署在 Google Endpoint 上。我有一个将数据插入数据库的发布请求。

我创建了一个脚本来使用此端点,但出现此错误:

{“detail”:“CSRF 失败:Referer 检查失败 - 无 Referer。”}

关于 over posts,我将 crsf_exempt 装饰器添加到我的类中,但它没有改变。
我尝试通过两种方式添加装饰器:

class AddUser(APIView):
    """ Create user and company from csv """

    @method_decorator(csrf_exempt)
    def post(self, request):


@method_decorator(csrf_exempt, name='dispatch')
class AddUser(APIView):
    """ Create user and company from csv """

    def post(self, request):
Run Code Online (Sandbox Code Playgroud)

但两者都失败了。

这是我联系端点的方式:

resp = requests.request(
    method, url,
    headers={'Authorization': 'Bearer {}'.format(
        open_id_connect_token)}, **kwargs)
Run Code Online (Sandbox Code Playgroud)

有任何想法吗 ?谢谢


编辑

因此,我尝试将身份验证类添加到我的视图中,但这似乎是一个坏主意。这对我来说真是麻烦。

我尝试让 csrftoken 这样做:

        client = requests.session()
        # Retrieve the CSRF token first
        client.get(url)  # sets cookie
        print(client.cookies)
        if 'csrftoken' in client.cookies:
            # Django 1.6 and up
            csrftoken = client.cookies['csrftoken']
        else:
            # older versions
            csrftoken = client.cookies
Run Code Online (Sandbox Code Playgroud)

事实是,我正在使用 IAP 来保护我的 API,并且我没有任何 csrftoken cookie,但我确实有一个如下所示的东西:

<RequestsCookieJar[<Cookie GCP_IAP_XSRF_NONCE_Q0sNuY-M83380ypJogZscg=1 为...

我如何使用它向我的 API 发出发布请求?

Kim*_*mor 0

在这个项目上工作一段时间后,这就是我学到的关于使用 Django 的 CSRF 的知识。

首先,如果您使用 django 模板,或者在后端和前端在同一服务器后面运行的任何情况下,最常见的做法是使用会话进行身份验证。默认情况下,DRF 会激活此功能。
这意味着在您的 DRF 配置中,如果您没有显式设置 DEFAULT_AUTHENTICATION_CLASSES 选项,默认身份验证将设置为 Session + BasicAuth。
在此配置中,您需要按照文档 ( https://docs.djangoproject.com/en/4.0/ref/csrf/ ) 中所述管理 CSRF 令牌。

如果您的后端和前端像我一样是分离的,那么使用 CSRF 并不是唯一的解决方案,甚至不是推荐的解决方案。在我的例子中,我在 IAP(身份感知代理,由 google 提供)后面使用 JWT。我必须编写自己的身份验证类,然后在我的 DRF conf 中使用它:

REST_FRAMEWORK = {

    'DEFAULT_AUTHENTICATION_CLASSES': [
      'main.authentication_backend.custom_auth.IAPAuthentication'],
    ...

}
Run Code Online (Sandbox Code Playgroud)

这里解释如何编写自己的身份验证类:https://www.django-rest-framework.org/api-guide/authentication/#custom-authentication