简体   繁体   English

使用Django csrf令牌填充Cookie

[英]Populate a cookie with a Django csrf token

i need to understand something. 我需要了解一些东西。

I've a rest server on server A (django-rest-framework). 我在服务器A(django-rest-framework)上有一个休息服务器。 An app on server B (angularjs) requests the rest server. 服务器B(angularjs)上的一个应用程序请求其余服务器。 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. 每次我请求h ttp://serverA/api-auth/login/ ,它都会返回403,因为我没有传递csrf令牌。

So, in my app.js, i've added : 因此,在我的app.js中,我添加了:

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

now, fine, i can send the csrf token. 现在,很好,我可以发送csrf令牌。 My question is, how can i populate the cookie ? 我的问题是,如何填充Cookie? Do i have to do a get() to obtain the token before posting ? 我必须在发布前做get()以获得令牌吗? Because currently my cookie is empty :( 因为当前我的cookie是空的:(

Thank you 谢谢

You cannot use SessionAuthentication method if you don't share the same domain. 如果您不共享同一域,则不能使用SessionAuthentication方法。 In your case the OAuth2Authentication is the way to go. 在您的情况下, OAuth2Authentication是必经之路。

Assuming your angularjs code using jquery ajax to post, you can put the csrf token into the meta tag 假设您使用jquery ajax来发布angularjs代码,则可以将csrf令牌放入meta标记中

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

Then setup your jquery ajax method to include the csrf token. 然后设置您的jquery ajax方法以包含csrf令牌。

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);
    }..............
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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