I can use KeycloakRestTemplate where one keycloak client is communicating with another keycloak client. However it only works if I have logged into the first ke
For my microservice architecture based application, I'm using both user and service accounts. I guess the spring security adapter only takes care of the user related stuff (the version I'm using, at least, which is 2.2.1). What I do is to have another RestTemplate, one which I handle myself in order to access resources as a client.
As an example:
@Service
public class RemoteAccessService{
//Manages user access
private KeycloakRestTemplate userAccessRestTemplate;
//Manages client access
private RestTemplate clientAccessRestTemplate;
public RemoteAccessService(KeycloakRestTemplate userAccessRestTemplate,
@Qualifier("clientAccessRestTemplate") RestTemplate clientAccessRestTemplate;){
}
}
Then, you build a RestTemplate bean in a @Configuration class in order to manage client authorization:
@Bean
public RestTemplate clientAccessRestTemplate() {
RestTemplate template = new RestTemplate();
template.getMessageConverters().add(new FormHttpMessageConverter());
template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
template.getInterceptors().add(new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
//Intercept each of the requests performed by this template
//and add the client access token in the Authorization header
HttpRequest wrapper = new HttpRequestWrapper(request);
if (clientAccessToken != null) {
wrapper.getHeaders().set("Authorization",
"Bearer " + clientAccessToken.getToken());
}
return execution.execute(wrapper, body);
}
});
return template;
}
Of course, you need to be sure you've got a proper clientAccessToken in the interceptor, you'll get a 401 or 403 code otherwise. Here you've got a post on how to perform this in OAuth (you don't need user/password, just client credentials).
As a sidenote, the keycloak adapters are handy to manage some situations, but they don't provide access to all the features of keycloak, which is a way more powerful.