1. 程式人生 > 其它 >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
只作為筆記