2
votes

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?

3
Is it possible to make experimental project reproducing the issue and share via git? it would be more clear how to help you resolve 401 code - Sergii

3 Answers

1
votes

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.

1
votes

the csrf only blocks requests of type post, put, delete ... that is, the get is free, therefore in order to obtain the token, first you have to make a request to a get method and extract the token from there that you would use to the next requests. in case the token is not generated, add this to the configure of your security configuration:

http.csrf (). csrfTokenRepository (CookieCrsfTokenRepository.withHttpOnlyFalse) .any () ........
0
votes

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.