简体   繁体   中英

Angular can't get CSRF cookie from Django

I did a lot of research on this topic, but it's still not working for me. I set my csrftoken cookie in Django,and it does in the response object.

But in any browser, it says no cookies in this site

Backend:

@ensure_csrf_cookie
def home(request):
    csrf_token = get_token(request)
    response = HttpResponse()
    response = render(request, 'index.html')
    response.set_cookie(key='csrftoken', value=csrf_token)
    return response

Angular:

myapp.config(function($httpProvider){
    //I use this when in angular1.0.x
    //$http.defaults.headers.post['X-CSRFToken'] = $cookies['csrftoken'];
    //now in angular1.2.x I use code below. but none of them works
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
});

When I do a POST I get message

Failed to load resource: the server responded with a status of 403 (FORBIDDEN)

Also if I print out header info in the $http error function:

console.log(header('Set-Cookie'));
console.log(header('Access-Control-Allow-Headers'));
console.log(header('Access-Control-Allow-Methods'));

all of these three are null .

I can't figure it why! Especially, it works fine in localhost , either Firefox or Chrome, but in an Apache server, always no cookie in this site.

Is there any setting should I do? Can anyone help my with this issue?

I'm not sure this will help, but your view is terribly written. You're trying to force the csrf in about five different ways, and you also have some redundant lines that don't do anything (you do response = HttpResponse() and then override it completely, making that line completely void). so there's a good chance one of them is screwing things over.

The point is - when you use render you don't need to do anything else to enforce the csrf (you know, except for making sure it's enabled). That's the point of using it over render_to_response . Try this much simpler version and see how much it helps:

def home(request):
    return render(request, 'index.html')

Please check the domain of the cookie set by Django.

Be aware of cross-domain requests.

$http docs : Angular provides a mechanism to counter XSRF, When performing XHR requests but will not be set for cross-domain requests.

Here is a small lib that might help you https://github.com/pasupulaphani/angular-csrf-cross-domain/blob/master/dist/angular-csrf-cross-domain.js

Try including the ngCookies module in your application.

myApp.run(function ($http, $cookies) {
    $http.defaults.headers.common['X-CSRFToken'] = $cookies.csrftoken;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM