我正在使用AngularJS和Django Rest Framework + Django CORS Headers开发1页应用程序。
我的问题是,当我联系后端时,“ csrftoken” cookie永远不会显示在浏览器中。
例如:我正在使用帖子进行登录。我正确地获得了“ sessionid” cookie,但是“ csrftoken”却没有显示,因此我无法从客户端进行适当的发布,因为由于缺少csrf令牌而被拒绝了。
来自前端/后端的一些代码片段。这些都是未完成的代码段,因此请不要挂在写得不好的代码上。
class LoginView(APIView): renderer_classes = (JSONPRenderer, JSONRenderer) def post(self, request, format=None): serializer = LoginSerializer(data=request.DATA) if serializer.is_valid(): userAuth = authenticate(username=serializer.data['username'], password=serializer.data['password']) if userAuth: if userAuth.is_active: login(request, userAuth) loggedInUser = AuthUserProfile.objects.get(pk=1) serializer = UserProfileSerializer(loggedInUser) user = [serializer.data, {'isLogged': True}] else: user = {'isLogged': False} return Response(user, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
.controller('LoginCtrl', ['$scope', '$http', 'uService', '$rootScope', function(scope, $http, User, rootScope) { scope.login = function() { var config = { method: 'POST', withCredentials: true, url: rootScope.apiURL+'/user/login/', data : scope.loginForm }; $http(config) .success(function(data, status, headers, config) { if (status == 200) { console.log(data[0]); //Test code // succefull login User.isLogged = true; User.username = data.username; } else { console.log(data); //Test code User.isLogged = false; User.username = ''; } }) .error(function(data, status, headers, config) { console.log('Testing console error'); User.isLogged = false; User.username = ''; }); };
}]);
任何有好的技巧/想法/例子的人吗?
因此,我找到了自己的解决方案,似乎效果很好。
这是我的代码的新片段:
class LoginView(APIView): renderer_classes = (JSONPRenderer, JSONRenderer) @method_decorator(ensure_csrf_cookie) def post(self, request, format=None): c = {} c.update(csrf(request)) serializer = LoginSerializer(data=request.DATA) if serializer.is_valid(): userAuth = authenticate(username=serializer.data['username'], password=serializer.data['password']) if userAuth: if userAuth.is_active: login(request, userAuth) loggedInUser = AuthUserProfile.objects.get(pk=1) serializer = UserProfileSerializer(loggedInUser) user = [serializer.data, {'isLogged': True}] else: user = {'isLogged': False} return Response(user, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
CORS_ALLOW_HEADERS = ( 'x-requested-with', 'content-type', 'accept', 'origin', 'authorization', 'X-CSRFToken'
)
而已!