其他分享
首页 > 其他分享> > 401 detail: "CSRF Failed: CSRF cookie not set

401 detail: "CSRF Failed: CSRF cookie not set

作者:互联网

出现原因
当您使用SessionAuthentication 时,您正在使用 Django 的身份验证,这通常需要检查 CSRF。Django REST Framework 强制执行此操作,仅适用于SessionAuthentication,因此您必须在X-CSRFToken标头中传递 CSRF 令牌。
出现场景
from rest_framework.authentication import SessionAuthentication

class CsrfExemptSessionAuthentication(SessionAuthentication):

def enforce_csrf(self, request):
    return  # To not perform the csrf check previously happening

代码解析:
编写一个类继承自 SessionAuthentication, 重写 enforce_csrf 方法,
如果返回一个 None,则代表不执行之前发生的 csrf 检查。

视图中使用:
class Object(APIView):
authentication_classes = (CsrfExemptSessionAuthentication, )

def post(self, request, format=None):
	pass

关于 csrf_exempt
关于其他网址所说的设置 csrf_exempt,那都是后面的操作,用户请求网站,首先要做的就是关于用户验证,
只有认证通过了,后续的操作才可以使用 csrf_exempt 来对视图进行 csrf 的豁免。

参考https://codeantenna.com/a/egu4oVNc01
只作为笔记

标签:set,401,视图,Django,SessionAuthentication,csrf,exempt,CSRF
来源: https://www.cnblogs.com/robert-zhou/p/16145839.html