我有以下代码:
问题是当我尝试访问user-login/时,我得到一个错误:"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 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发布于 2013-07-02 19:12:49
我假设您使用的是django rest框架SessionBackend。这个后端执行一个implicit CSRF check
您可以通过以下方式来避免这种情况:
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
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("/")发布于 2015-02-03 21:45:36
实际上,在SessionAuthentication中禁用csrf检查的更好方法是:
from rest_framework.authentication import SessionAuthentication as OriginalSessionAuthentication
class SessionAuthentication(OriginalSessionAuthentication):
def enforce_csrf(self, request):
return发布于 2015-10-18 02:12:48
解决这个问题的最简单方法是:
为此,在drf see drf auth中有两种身份验证方法
BasicAuthentication
SessionAuthentication (默认)
SessionAuthentication有一个强制的csrf检查,但是BasicAuthentication没有,所以我的方法是在我的视图中使用BasicAuthentication而不是SessionAuthentication。
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({})https://stackoverflow.com/questions/16501770
复制相似问题