CSRF豁免失败 - APIView csrf django休息框架 [英] CSRF Exempt Failure - APIView csrf django rest framework

查看:427
本文介绍了CSRF豁免失败 - APIView csrf django休息框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

问题是当我尝试访问user-login /我收到一个错误:
CSRF失败:CSRF没有设置cookie

The problem is when I try to access user-login/ I get an error: "CSRF Failed: CSRF cookie not set."

我可以做什么?

我正在使用django休息框架。 p>

I am using the django rest framework.

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休息框架 SessionBackend 。此后端执行隐性CSRF检查

I assume you use the django rest framework SessionBackend. This backend does a implicit CSRF check

您可以通过以下方式避免这种情况:

You can avoid this by:

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)

并将其设置为 authentication_classes 在您的视图

And set this as authentication_classes in your View

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("/")

这篇关于CSRF豁免失败 - APIView csrf django休息框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆