Python CSRF豁免故障-APIView CSRF django rest框架
我有以下代码: 问题是,当我尝试访问用户登录/I时出现错误: “CSRF失败:未设置CSRF cookie。” 我能做什么 我正在使用django rest框架Python CSRF豁免故障-APIView CSRF django rest框架,python,django,django-rest-framework,Python,Django,Django Rest Framework,我有以下代码: 问题是,当我尝试访问用户登录/I时出现错误: “CSRF失败:未设置CSRF cookie。” 我能做什么 我正在使用django rest框架 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 n
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 rest框架。此后端执行以下操作: 您可以通过以下方式避免这种情况:
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("/")
实际上,禁用SessionAuthentication内部csrf检查的更好方法是:
from rest_framework.authentication import SessionAuthentication as OriginalSessionAuthentication
class SessionAuthentication(OriginalSessionAuthentication):
def enforce_csrf(self, request):
return
解决此问题的最简单方法是: 因此,在drf中有两种身份验证方法 基底动脉造影 会话身份验证(默认) SessionAuthentication具有强制csrf检查,但BasicAuthentication没有。 因此,在我看来,我的方法是使用基本身份验证,而不是会话身份验证
from rest_framework.authentication import BasicAuthentication
class UserLogin(generics.CreateAPIView):
permission_classes = (permissions.AllowAny,)
serializer_class = UserSerializer
authentication_classes = (BasicAuthentication,)
def post(self, request, *args, **kwargs):
return Response({})
最好是让enforce_csrf检查什么都不做:
from rest_framework.authentication import SessionAuthentication
class UnsafeSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, *args, **kwargs):
'''
Bypass the CSRF checks altogether
'''
pass
否则,如果上游authenticate()方法发生更改,将来可能会出现问题。而且,让支票不做任何事情要简单得多:-)