I have to create another simple html page for the JHipster, and it has to execute AJAX requests. It contains a tiny AngularJS app, so I copied some of the JHipster code:
var app = angular.module('app', ['dep1', 'dep2', 'dep3']);
app.config(function ($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'CSRF-TOKEN';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRF-TOKEN';
});
Then I execute HTTP requests like this:
$http.post("/controller/execute", {code: ourCode})
And that generates an error. However, then I reload the page and everything works like a charm. Then I grep'ed the sources and found that in auth.session.service.js you use following code to obtain a CSRF token:
$http.get('api/account');
I added this snippet to my webapp and it works great now.
However I wonder if there's a better solution (avoiding the extra request?). I suspect the question is too broad, but can't think how to make it simple.
By default, JHipster handles CSRF properly, using Spring Security on the server-side and AngularJS on the client-side.
As you said you just copied some code from JHipster: are you really using JHipster, or just copy/pasting the client-side code? This won't work if you don't have a server correctly configured, that's where our work is.
Normally you shouldn't have to copy/paste that AngularJS configuration, we do all that for you.