如何仅在某些情况下禁用 Django 的 csrf 保护? [英] How can I disable Django's csrf protection only in certain cases?

查看:32
本文介绍了如何仅在某些情况下禁用 Django 的 csrf 保护?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 Django 编写一个站点,其中 API URL 与面向用户的 URL 相同.但是我遇到了使用 POST 请求和 CSRF 保护的页面的问题.例如,如果我有一个页面/foo/add,我希望能够以两种方式向它发送 POST 请求:

I'm trying to write a site in Django where the API URLs are the same as user-facing URLs. But I'm having trouble with pages which use POST requests and CSRF protection. For example, if I have a page /foo/add I want to be able to send POST requests to it in two ways:

  1. 作为最终用户(使用会话 cookie 进行身份验证)提交表单.这需要 CSRF 保护.
  2. 作为 API 客户端(使用 HTTP 请求标头进行身份验证).如果启用 CSRF 保护,这将失败.

我找到了各种禁用 CSRF 的方法,例如@csrf_exempt,但这些方法都对整个视图禁用了它.有没有办法在更细粒度的级别启用/禁用它?还是我只需要从头开始实施自己的 CSRF 保护?

I have found various ways of disabling CSRF, such as @csrf_exempt, but these all disable it for the entire view. Is there any way of enabling/disabling it at a more fine-grained level? Or am I just going to have to implement by own CSRF protection from scratch?

推荐答案

Django 的 CSRF Protection 文档中有一节名为 视图需要对一条路径进行保护,其中描述了一种解决方案.这个想法是在整个视图上使用 @csrf_exempt,但是当 API 客户端标头不存在或无效时,则调用一个函数用 @csrf_protect 注释.

There is a section of Django's CSRF Protection documentation titled View needs protection for one path which describes a solution. The idea is to use @csrf_exempt on the whole view, but when the API client header is not present or invalid, then call a function annotated with @csrf_protect.

这篇关于如何仅在某些情况下禁用 Django 的 csrf 保护?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆