Search code examples
angularjsjspspring-securitycsrf

How send POST request in angularjs with _csrf?


I want sending POST requests to service under spring security. if i using form submission (with hidden input) - it's working fine. But i don't know, how send request with $http.post. my form:

<form method="POST" type="submit" action="http://localhost:8888/rest/post1" />
    <button>345</button>
    <input name="${_csrf.parameterName}"
           value="${_csrf.token}" />
</form>

it work.

I save params:

<script>
        var a = "${_csrf.parameterName}";
        var b = "${_csrf.token}";
</script>

My ng-click function:

$http.post('http://localhost:8888/rest/post1', {"_csrf": b}, {
    "headers" :
    { "_csrf" : b }
}).success(function(data) {
    console.log("ok");

}).error(function(){

    console.log("no");
});

It always writing "no".

I think, that need to send variable as webForm, but how do it in $http.post?

Fiddler write: Content-Type is 'application/json'; this inspector supports 'x-www-form-urlencoded' only

Server console:

org.springframework.web.servlet.PageNotFound handleHttpRequestMethodNotSupported
WARNING: Request method 'POST' not supported

Help me, please!


Solution

  • I solved this)

    var request = $http({
        method: "post",
        url: "http://localhost:8888/rest/post1",
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        transformRequest: function(){return a+"="+b;},
        data: {}
    });