2

Using Jersey 2.19, How do I get a CSRF token from a server which uses Spring Security 3 and make a successful login? I have two projects, a client which uses REST, and a server which was created using JHipster.

First, I'm making a get request to http://localhost:8080 and I'm getting this response headers:

Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Language:en
Content-Length:17229
Content-Type:text/html;charset=utf-8
Date:Tue, 21 Jul 2015 19:24:40 GMT
Expires:0
Last-Modified:Thu, 02 Jul 2015 17:07:31 GMT
Pragma:no-cache
Server:Apache-Coyote/1.1
Set-Cookie:CSRF-TOKEN=0902449b-bac7-43e8-bf24-9ec2c1faa48b; Path=/
X-Application-Context:application:dev:8081
X-Content-Type-Options:nosniff
X-XSS-Protection:1; mode=block

I extract the Set-Cookie header and I get the CSRF token from there. Then I'm making a post request this way:

http://localhost:8080/api/authentication?j_username=user&j_password=user&submit=Login

With this request headers:

Content-Type: application/x-www-form-urlencoded
X-CSRF-TOKEN: <extracted token>

Using Chrome's plugin postman, I can make a correct post request for login, but with Jersey, I'm unable to send correctly the CSRF token (I get 403 response).

This is the response:

{"timestamp":1437507680089,"status":403,"error":"Forbidden","message":"Expected CSRF token not found. Has your session expired?","path":"/api/authentication"}

This is the jersey code:

WebTarget hostTarget = getClient().target("http://localhost:8080");

Response r = hostTarget.request().get();
String header = r.getHeaderString("Set-Cookie");
String csrf = null;

List<HttpCookie> cookies = HttpCookie.parse(header);

for (HttpCookie c : cookies) {
    if("CSRF-TOKEN".equals(c.getName())){
        csrf = c.getValue();
        break;
    }
}

WebTarget loginTarget = hostTarget.path("/api/authentication");
loginTarget = loginTarget.queryParam("j_username", username)
    .queryParam("j_password", password)
    .queryParam("submit", "Login");

Builder req = loginTarget.request(MediaType.APPLICATION_JSON_TYPE);
if (csrf != null) {
    req = req.header("X-CSRF-TOKEN", csrf);
}

Response cr = req.post(Entity.entity(null,
        MediaType.APPLICATION_FORM_URLENCODED_TYPE));

System.out.println("Response: " + cr.readEntity(String.class));

Thanks for your time.

2
  • 1
    Have you checked while sending through postman that the CSRF cookie token is not available? Maybe the call succeeded as a cookie was available with the token Jul 21, 2015 at 20:27
  • Using postman, if I omit the X-CSRF-TOKEN I get "403 Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'." Using _csrf as request parameter or the mentioned header works with postman. Nevertheless, when I omit the CSRF token usage in the client code I still get the 403 response mentioned in the question.
    – dovahkiin
    Jul 21, 2015 at 21:25

1 Answer 1

1

After much trial and error, I found the solution. Is important to take in count cookies (as indicated by Roman Vottner) for REST configuration to communicate with spring security. The important cookie that must be present is JSESSIONID and the header X-CSRF-TOKEN (or whatever header name is configured in the server), so capture them in a initial request and send them again.

I've decided to send all the cookies to the server in this way.

WebTarget hostTarget = getClient().target("http://localhost:8080");

Response r = hostTarget.request().get();
String headerCookies = r.getHeaderString("Set-Cookie");

Map<String, NewCookie> cookies = r.getCookies();
String csrf = cookies.get("CSRF-TOKEN").getValue();

WebTarget loginTarget = hostTarget.path("/api/authentication");
loginTarget = loginTarget.queryParam("j_username", username)
    .queryParam("j_password", password)
    .queryParam("submit", "Login");

Builder req = loginTarget.request(MediaType.APPLICATION_JSON_TYPE);
req = req.header("Cookie", headerCookies);

if (csrf != null) {
    req = req.header("X-CSRF-TOKEN", csrf);
}

Response cr = req.post(Entity.entity(null,
        MediaType.APPLICATION_FORM_URLENCODED_TYPE));

//The response is empty (in my case) with status code 200
System.out.println("Response: " + cr.readEntity(String.class));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.