sinedsem
sinedsem

Reputation: 5723

How to provide the CSRF Token in single page application (spring security)?

When I try to load part of a page using ajax I got 403 error

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

Spring Security FAQ tells us

If an HTTP 403 Forbidden is returned for HTTP POST, but works for HTTP GET then the issue is most likely related to CSRF. Either provide the CSRF Token or disable CSRF protection (not recommended).

So, how can a do this?

function getPage(url) {
    $.ajax({
        type: 'POST',
        url: url,
        data: {_csrf: "??"},
        success: function (data) {
            loadPage(url, data);
        }
    });
}

Upvotes: 3

Views: 2790

Answers (2)

sinedsem
sinedsem

Reputation: 5723

Found an answer to my own question here: http://spring.io/blog/2013/08/21/spring-security-3-2-0-rc1-highlights-csrf-protection/

this - to html

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

this - to js

$(function () {
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    $(document).ajaxSend(function(e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });
});

Upvotes: -2

Mace
Mace

Reputation: 1089

You can get the token from the cookie which is stored at your client. For that you have to use something like this cookie-service: https://www.npmjs.com/package/angular2-cookie

write a function like this to get the token:

getCookie(){
    return this._cookieService.get("token-name");
}

Finaly add the token to the request header:

doSomething(token){
    var json = JSON.stringify({});
    var headers = new Headers();
    headers.append('Content-Type','application/json');
     headers.append('token-name', token);
    return this._http.post('http://localhost:8080/doSomething', json, {
        headers: headers
    }).map(res => res.text()
    );
}

This solved the problem for me

Upvotes: 0

Related Questions