当前位置:  开发笔记 > 编程语言 > 正文

CSRF豁免失败 - APIView csrf django休息框架

如何解决《CSRF豁免失败-APIViewcsrfdjango休息框架》经验,为你挑选了2个好方法。



1> maersu..:

我假设你使用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("/")



2> Alexander Ar..:

实际上,在SessionAuthentication中禁用csrf检查的更好方法是:

from rest_framework.authentication import SessionAuthentication as OriginalSessionAuthentication

class SessionAuthentication(OriginalSessionAuthentication):
    def enforce_csrf(self, request):
        return

推荐阅读
地之南_816
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有