Reputation: 8056
I am using the angular.js and csrf (Cross-site request forgery).
I have added the angular cookie file.
script src="angular-cookies.js"
And then, to load it in the application:
angular.module('myApp', ['ngCookies']);
It’s really easy to add the CSRF token in the headers of the $http service. We just need to configure it into the run process of the application, requiring the $cookie and $http services.
.run(function ($http, $cookies) {
$http.defaults.headers.post['x-csrf-token'] = $cookies._csrf;
});
in the browser debug console, I can find the cookie is existing. However,when the page is loaded, $cookies outputs undefined, it is strange the $cookies object itself is undefined, but obviously I have loaded the cookie.js and inject the module into the application
This is on the node.js server side, which how I set a CSRF token on the cookie
app.use(require('csurf')());
app.use(function(req, res, next){
res.locals.token = req.csrfToken();
res.cookie('XSRF_TOKEN', req.csrfToken(),{ maxAge: 900000, httpOnly: false });
next();
});
Thanks for the reminding, I changed the
res.cookie('XSRF_TOKEN', req.csrfToken(),{ maxAge: 900000 });
to
res.cookie('XSRF_TOKEN', req.csrfToken(),{ maxAge: 900000, httpOnly: false });
so the cookie is readable from the browser.
Upvotes: 2
Views: 1563
Reputation: 4086
According to angularJS documentation
Your server needs to set a token in a JavaScript readable session cookie called XSRF-TOKEN on the first HTTP GET request.
This cookie must be readable with Javascript, and ideally sent with the index.html page.
When this is done, you should see it in your browser (options / cookies ...)
At this point, you should access it in your angular code.
If this is not the case, may you should try to access it with pure Javascript
_getCookie = function(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++){
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
};
getCookie("XRSF_TOKEN");
Upvotes: 3
Reputation: 12410
Your cookie is probably being set as HttpOnly = true which will set the cookie but will not allow the client to view it therefore it comes back as undefined. You will need to make sure this flag is set to false.
Upvotes: 3