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

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

问题描述

我试图写在Django一个网站,该API网址是一样的面向用户的URL。但我有与使用POST请求和CSRF保护页面的麻烦。举例来说,如果我有一个页面/富/加我希望能够到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_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保护文档的某个章节href=\"https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#view-needs-protection-for-one-path\">View需要保护它描述了一个解决方案,一个路径。我们的想法是使用 @csrf_exempt 的全貌,但是当客户端API头是不是present或无效,则调用一个函数
@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天全站免登陆