Django REST即使使用TokenAuthentication也要求CSRF令牌 [英] Django REST asks for CSRF token even with TokenAuthentication

查看:45
本文介绍了Django REST即使使用TokenAuthentication也要求CSRF令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为移动和Web环境构建服务器,并且我希望同时具有会话身份验证和令牌身份验证.但是,这些似乎彼此矛盾.对于这两种方案的登录,我都有不同的看法.

I am building a server for both mobile and web environments and I want to have session auth alongside with token auth. However, these seem to be at odds with each other. I have a different view for logins in both schemes.

如果我以用户可浏览的API身份登录,然后发送另一个用户的令牌登录请求,则服务器会抱怨没有CSRF令牌.但是,如果我注销,突然就没问题了.

If I log in as a user inside the browsable API and then send a request for token login for a different user, the server complains that there is no CSRF token. However if I log out, suddenly there's no problem.

我不确定在实现前端并且登录来自不同设备之后,情况有多严重,但是到目前为止看起来还不太好.

I am not sure how severe it will be after frontend is implemented and the logins come from different devices, but so far it doesn't look good.

如果传递了正确的 Authorization:Token< token> 标头,有什么想法如何停止要求CSRF令牌?还是针对我的问题的其他解决方案?

Any idea how to stop requiring CSRF token if the correct Authorization: Token <token> header is passed? Or different solution to my problem?

推荐答案

默认 SessionAuthentication 后端的构建方式是,如果您在请求中提供有效的会话,它将打开CSRF验证.有两种可能的解决方案:要么不一起使用两种身份验证方法(在请求中发送有效会话cookie时不使用令牌),要么通过将 TokenAuthentication 后端放在< DEFAULT_AUTHENTICATION_CLASSES 设置中的code> SessionAuthentication .

Default SessionAuthentication backend from DRF is built in a way that if you provide valid session in request, it will turn on CSRF validation. There are 2 possible solutions for that: either don't use two authentications method together (don't use token when you are sending valid session cookie in request) or prioritize token authentication by putting TokenAuthentication backend above SessionAuthentication in DEFAULT_AUTHENTICATION_CLASSES setting.

这篇关于Django REST即使使用TokenAuthentication也要求CSRF令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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