Django Rest Framework关闭CSRF验证

detail": "CSRF Failed: CSRF cookie not set

如果你使用DRF出现了上面的报错,而试过网上所说的注释掉setting里面的CSRF中间件,依然无效的话,尝试一下下面的方法。

 

SessionAuthenticationDRF使用的默认方案。DRF SessionAuthentication使用Django的会话框架进行身份验证,需要检查CSRF。

'DEFAULT_AUTHENTICATION_CLASSES'= ( 
    'rest_framework.authentication.SessionAuthentication', 
    'rest_framework.authentication.BasicAuthentication' 
),
如果需要关闭CSRF,
from rest_framework.authentication import SessionAuthentication, BasicAuthentication  
 
class CsrfExemptSessionAuthentication(SessionAuthentication): 
 
    def enforce_csrf(self, request): 
        return  # To not perform the csrf check previously happening
在views加入
authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)
posted @ 2018-07-24 21:04  青花メ  阅读(1207)  评论(0编辑  收藏  举报