为什么会发生此错误?
发生这种情况是由于
SessionAuthenticationDRF使用默认方案。DRF
SessionAuthentication使用Django的会话框架进行身份验证,该框架要求检查CSRF。
当你
authentication_classes在视图/视图集中未定义任何对象时,DRF将此身份验证类用作默认身份验证类。
'DEFAULT_AUTHENTICATION_CLASSES'= ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication'),
由于DRF需要对同一视图同时支持基于会话和基于非会话的身份验证,因此DRF仅对经过身份验证的用户强制执行CSRF检查。这意味着只有经过身份验证的请求才需要CSRF令牌,并且匿名请求可以在没有CSRF令牌的情况下发送。
如果你将AJAX样式的API与
SessionAuthentication一起使用,则需要为任何“不安全的” HTTP方法调用(例如
PUT, PATCH, POST or DELETe请求)包括有效的CSRF令牌。
那该怎么办呢?
现在要禁用csrf检查,你可以创建
CsrfExemptSessionAuthentication从默认
SessionAuthentication类扩展的自定义身份验证类。在此身份验证类中,我们将覆盖
enforce_csrf()在实际内部进行的检查
SessionAuthentication。
from rest_framework.authentication import SessionAuthentication, BasicAuthentication class CsrfExemptSessionAuthentication(SessionAuthentication): def enforce_csrf(self, request): return # To not perform the csrf check previously happening
在你看来,然后可以将定义authentication_classes为:
authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)
这应该处理csrf错误。



