Spring MVC 4 AngularJS 1.3 HTTP POST has null CSRF token or header

When I disable CSRF protection then all my POST requests sent by AngularJS are accepted, but when it's enabled I receive the following error:

ERROR:

HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.

From what I understood, the request doesn't send any content to match _csrf token or the header isn't set.

I have this in my HTML header code:

<head>
  (...)
  <meta name="_csrf" content="${_csrf.token}"/>
  <meta name="_csrf_header" content="${_csrf.headerName}"/>
  (...)
</head>

I looked at questions concerning CSRF and Spring that were posted here, but I unfortunately didn't manage to solve my problem although I tried to use various code samples posted as solutions.

I think that I should somehow send the CRSF data with my POST request, but I don't have any idea how to do it.

I'll appreciate any help :)

Have you seen the documentation on angularJS $http and XSRF-token (same thing):

https://docs.angularjs.org/api/ng/service/$http scroll down to Cross Site Request Forgery (XSRF) Protection

You can configure AngularJs to automatically handle it:

The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName properties of either $httpProvider.defaults at config-time, $http.defaults at run-time, or the per-request config object.

I wonder why you want to use CSRF protection in a controller that is written to have a javascript front end. CSRF goal is to avoid that another site will send a redirect post query with unwanted data. If you use AngularJs to get the csrf protected taken, any evil site will be able to send to a browser the javascript code to first get the token and then post the unwanted data. IMHO, you should not rely on CSRF protection when using Ajax.

You can try to change name="_csrf" to name="csrf". It seems like underscores aren't allowed in Laravel. This is the case if talking about headers.

For example:

$token = Request::header('_csrf'); // Not working

$token = Request::header('csrf'); // Working!


Note that the above applies to Laravel 4.2