org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 : [no body]
fintans opened this issue · 2 comments
I am trying to run an integration test. When I add the Auth header, I get the above error. When I remove the auth header, the test passes. I have removed any authentication on my end points just so I can try get this working.
I have downgraded to sring-boot 2.4.4
as suggested in other discussion threads.
The jwt is being successfully created, but when I add it to auth headers, I get the 401
error
@Test
public void test_endpoint2() {
KeycloakMock mock = new KeycloakMock(aServerConfig().withDefaultHostname("http://localhost").withPort(8000).withDefaultRealm("SpringBootKeycloak").build());
mock.start();
RestTemplate restTemplate1 = new RestTemplate();
String token = mock.getAccessToken(aTokenConfig().build());
String fullToken = "Bearer " + token;
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
HttpHeaders headers = request.getHeaders();
headers.set("Authorization", fullToken);
headers.set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
return execution.execute(request, body);
};
restTemplate1.setInterceptors(Arrays.asList(interceptor));
String url = "http://localhost:" + port + "/api/test2";
ResponseEntity<String> customerResponse = restTemplate1.getForEntity(url, String.class);
assertThat(customerResponse.getStatusCode(), Matchers.is(HttpStatus.OK));
}
Error logs:
2021-12-18 12:40:43.496 INFO 7640 --- [ntloop-thread-0] c.t.k.impl.handler.CommonHandler : 200: GET /auth/realms/SpringBootKeycloak/.well-known/openid-configuration
2021-12-18 12:40:43.560 INFO 7640 --- [o-auto-1-exec-1] o.keycloak.adapters.KeycloakDeployment : Loaded URLs from http://localhost:8000/auth/realms/SpringBootKeycloak/.well-known/openid-configuration
2021-12-18 12:40:43.612 INFO 7640 --- [ntloop-thread-0] c.t.k.impl.handler.CommonHandler : 200: GET /auth/realms/SpringBootKeycloak/protocol/openid-connect/certs
org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 : [no body]
applicaction.properties:
keycloak.auth-server-url=http://localhost:8000/auth
keycloak.realm=SpringBootKeycloak
keycloak.resource=login-app
keycloak.public-client=true
keycloak.bearer-only=true
I am not (yet) authenticating the above endpoint in security config
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.antMatchers("/api/hello")
.hasRole("user").anyRequest().authenticated();
http.csrf().disable();
}
As far as I can see, the issue is with the server configuration: you use withDefaultHostname("http://localhost")
, but the hostname is not supposed to contain the protocol part. Please use withDefaultHostname("localhost")
and see if it works.
This was the problem! Thank you so much.