如何仅在某些情况下禁用 Django 的 csrf 保护?

编程入门 行业动态 更新时间:2024-10-11 21:23:43
本文介绍了如何仅在某些情况下禁用 Django 的 csrf 保护?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试用 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:

作为最终用户(使用会话 cookie 进行身份验证)提交表单.这需要 CSRF 保护.作为 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-18 15:42:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/942127.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:情况下   在某些   csrf   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!