CSRF 豁免失败 - APIView csrf django Rest Framework

2023-11-21

我有以下代码:

问题是当我尝试访问用户登录/时出现错误: “CSRF 失败:CSRF cookie 未设置。”

我能做些什么?

我正在使用 django 休息框架。

urls.py:

url(r'^user-login/$', 
    csrf_exempt(LoginView.as_view()),
    name='user-login'),

views.py:

class LoginView(APIView):
"""
List all snippets, or create a new snippet.
"""
def get(self, request, format=None):
    startups = Startup.objects.all()
    serializer = StartupSerializer(startups, many=True)
    return Response(serializer.data)

def post(self, request, format=None):
    profile = request.POST

    if ('user_name' not in profile or 'email_address' not in profile or 'oauth_secret' not in profile):
        return Response(
            {'error': 'No data'},
            status=status.HTTP_400_BAD_REQUEST)

    username = 'l' + profile['user_name']
    email_address = profile['email_address']
    oauth_secret = profile['oauth_secret']
    password = oauth_secret

我假设你使用 django 休息框架会话后端。这个后端做了一个隐式 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)

并将其设置为身份验证类在你看来

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("/")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

CSRF 豁免失败 - APIView csrf django Rest Framework 的相关文章

随机推荐