问题描述
我使用的Django和休息框架+ Django的CORS头发展中AngularJS 1页的申请书。
I am developing a 1-page application in AngularJS using and Django Rest Framework + Django CORS Headers.
我的问题是,csrftoken曲奇在我的浏览器一直没有出现,当我所接触的后端。
My problem is that the "csrftoken" cookie never shows up in my browser when I have contacted the backend.
例如:我做的使用后登录。我得到的SessionID的曲奇正确,但csrftoken一直没有出现并为此我无法从我的客户做适当的职位,因为我会得到应有的缺乏CSRF令牌被拒绝。
For example: I am doing a login using a post. I get the "sessionid" cookie properly but the "csrftoken" never shows up and therefor I cannot do proper posts from my client since I will get denied due the lack of the csrf token.
- 我已经分析了来自API的响应头和csrftoken不是疗法。
- 我在REST API浏览器直接观看,它显示了罚款那里。
- 只是想指出,我可以做我的第一篇登录以来的Django的REST框架只CSRF强制验证用户。如果我尝试重新登录,因为SessionID的-cookie它present将失败。
- 我不是绕过CSRF保护计算器上提出了一些帖子interessted。
这是前/后端一些code片段。这些都是疲于奔命的片段,所以不要让她挂在写得不好code。
Some code snippets from front/backend. These are unfinnished snippets, so dont get hung up on poorly written code.
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)
客户端AngularJS登录控制器
.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 = '';
});
};
}]);
任何人只要有任何好的建议/创意/例子吗?
Anyone with any good tips/ideas/examples?
推荐答案
所以,我发现我自己的解决方案,这一点,似乎工作太棒了。
So I found my own solution to this, seems to work great.
这是我的code的新片段:
This is the new snippets of my code:
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)
AngularJS客户端(添加令牌请求头)
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
服务器端设置文件(特异性地Django的-CORS-头)
第5默认情况下添加,但你需要添加X-CSRFToken允许从客户端的API,这样的标题采用CORS,否则职位将被拒绝。
CORS_ALLOW_HEADERS = (
'x-requested-with',
'content-type',
'accept',
'origin',
'authorization',
'X-CSRFToken'
)
完蛋了!
这篇关于AngularJS +的Django的REST框架+ CORS(CSRF的Cookie没有出现在客户端上)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!