Get XSRF-TOKEN using Spring RestTemplate

I’m trying to call a service which has CSRF enabled and all it’s endpoints are configured to request authentication header from the user.

I’m using Spring RestTemplate as follows:

 ResponseEntity<String> responseEntity = getRestTemplate().exchange(
      "localhost:9090/",
       "HEAD",
       entity,
       String.class);
return responseEntity.getBody();

However, I’m not able to read the Headers from the response as I’m getting HTTP 401 error.

My workaround is to read the token from the exception that RestTemplate throws HttpClientErrorException. Like this:

exception.getResponseHeaders().get("Set-Cookie");
for (String header : headers) {
   if (header.startsWith("XSRF-TOKEN")) {
        token = header.split("=")[1];
        break;
    }
}

Is there any way to get XSRF-TOKEN token with out relying on reading it from the exception?

XSRF-TOKEN following spring specification is marker for header by default. So you should try get it in this way:

List tokenList = responseEntity.getHeaders().get("XSRF-TOKEN");

This collection consist of single element as usual, so first element should be your token.

You are not getting an exception when accessing with GET method. Hence, I would create a get endpoint for retrieving the token and then use it for next POST calls.

Hope that approach makes sense.