Django REST即使使用TokenAuthentication也要求CSRF令牌

编程入门 行业动态 更新时间:2024-10-26 04:20:39
本文介绍了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令牌

本文发布于:2023-10-29 09:40:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539363.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:令牌   REST   Django   CSRF   TokenAuthentication

发布评论

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

>www.elefans.com

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