简体   繁体   中英

Populate a cookie with a Django csrf token

i need to understand something.

I've a rest server on server A (django-rest-framework). An app on server B (angularjs) requests the rest server. I want to add authentication. each time i request h ttp://serverA/api-auth/login/ , it returns 403 because i don't pass the csrf token.

So, in my app.js, i've added :

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

now, fine, i can send the csrf token. My question is, how can i populate the cookie ? Do i have to do a get() to obtain the token before posting ? Because currently my cookie is empty :(

Thank you

You cannot use SessionAuthentication method if you don't share the same domain. In your case the OAuth2Authentication is the way to go.

Assuming your angularjs code using jquery ajax to post, you can put the csrf token into the meta tag

<!--<meta name="csrf-token" content="{{csrf_token}}">-->

Then setup your jquery ajax method to include the csrf token.

jQuery(document).ajaxSend(function(event, xhr, settings) {
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        //var token = $('meta[name="csrf-token"]').attr('content');
        var csrftoken = $.cookie('csrftoken');
        xhr.setRequestHeader("X-CSRFToken", 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