I have a spring boot REST Service which offers some methods. They are protected by CSRF and Username / Password Basic Auth (https).
But when I try to do a POST Request it fails with Status Code 403 and Message "Could not verify the provided CSRF token because your session was not found"
That's my client code:
ApiMessage msg = new ApiMessage("Client1", "Key1", "Value1");
// Set up Basic Authentication
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder()
.nonPreemptive()
.credentials(ApiUser, ApiUserPassword)
.build();
ClientConfig clientConfig = new ClientConfig();
clientConfig.register(feature);
Client client = ClientBuilder.newClient(clientConfig);
// Set up client and target (ApiHost = URI for the request Ressource)
WebTarget target = client.target(ApiHost);
WebTarget checkTarget = target.path("check");
Invocation.Builder invocationBuilder = checkTarget.request(MediaType.APPLICATION_JSON);
// Do a first request to get the CSRF Header
Response response = invocationBuilder.post(Entity.entity(msg, MediaType.APPLICATION_JSON));
if (response.getStatus() == 200) {
System.out.println("Without CSRF - everything worked. ");
} else if (response.getStatus() == 403) {
System.out.println("CSRF Protection: " + response.getStatus() + response.readEntity(String.class));
// Get CSRF Token out of the response
Map<String, NewCookie> cookies = response.getCookies();
String csrf = cookies.get("XSRF-TOKEN").getValue();
// Add the Token to the header and POST again
invocationBuilder.header("X-XSRF-TOKEN", csrf);
response = invocationBuilder.post(Entity.entity(msg, MediaType.APPLICATION_JSON));
if (response.getStatus() != 200) {
System.out.println("Error: " + response.getStatus() + response.readEntity(String.class));
} else {
System.out.println("With CSRF - everything worked. ");
}
} else {
System.out.println(response.getStatus() + " " + response.readEntity(String.class));
}
The first request ends with Status 403 and message "Could not verify the provided CSRF token because your session was not found". After that I extract the CSRF Token successful out of the response header. But the second request with CSRF header fails with the same error.
Doing the same in Postman works fine.
Any ideas where is my mistake and what I am doing wrong?