我假设你使用django rest框架SessionBackend.此后端执行隐式CSRF检查
您可以通过以下方式避免此
from rest_framework.authentication import SessionAuthentication class UnsafeSessionAuthentication(SessionAuthentication): def authenticate(self, request): http_request = request._request user = getattr(http_request, 'user', None) if not user or not user.is_active: return None return (user, None)
并在View 中将其设置为authentication_classes
class UnsafeLogin(APIView): permission_classes = (AllowAny,) #maybe not needed in your case authentication_classes = (UnsafeSessionAuthentication,) def post(self, request, *args, **kwargs): username = request.DATA.get("u"); password = request.DATA.get("p"); user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("/")
实际上,在SessionAuthentication中禁用csrf检查的更好方法是:
from rest_framework.authentication import SessionAuthentication as OriginalSessionAuthentication class SessionAuthentication(OriginalSessionAuthentication): def enforce_csrf(self, request): return