拥有可 POST 的 API 和 Django 的 CSRF 中间件 [英] Having a POST'able API and Django's CSRF Middleware

查看:28
本文介绍了拥有可 POST 的 API 和 Django 的 CSRF 中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Django Web 应用程序,它具有前端、可通过 Web 访问的组件和可由桌面客户端访问的 API.但是,现在使用新的 CSRF 中间件组件,来自桌面客户端的 API 请求通过 POST 得到 403.

I have a Django webapp that has both a front-end, web-accessible component and an API that is accessed by a desktop client. However, now with the new CSRF middleware component, API requests from the desktop client that are POST'ed get a 403.

我理解为什么会发生这种情况,但是在不影响安全性的情况下解决此问题的正确方法是什么?有什么办法可以在 HTTP 标头中表明这是一个 API 请求并且 Django 不应该检查 CSRF 或者这是一个糟糕的策略吗?

I understand why this is happening, but what is the proper way to fix this without compromising security? Is there someway I can signal in the HTTP header that it's an API request and that Django shouldn't be checking for CSRF or is that a bad strategy?

编辑--

我目前使用的方法是桌面客户端设置一个标头,X-Requested-With:XMLHttpRequest.这有点 hacky,但我不确定如何更好地处理.

The method I'm using at the moment is that the desktop client sets a header, X-Requested-With: XMLHttpRequest. This is kinda hacky, but I'm not sure how this would be handled better.

推荐答案

如何为您的桌面客户端拆分一个视图并使用 csrf_exempt?

How about just splitting off a view(s) for your desktop client and decorating them with csrf_exempt?

这篇关于拥有可 POST 的 API 和 Django 的 CSRF 中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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