I have the following Setup:
Keycloak 9.0.0 running on port 8180
Spring Boot server application running on port 8080
Demo client application using CxfTypeSafeClientBuilder
to access server service
The Keycloak - Spring Boot interaction is working fine and I can receive tokens from Keycloak and the demo service is validating the token if I pass it as Authorization
header.
How should I configure the CxfTypeSafeClientBuilder
/ RestClientBuilder
to handle the JWT tokens I get from the Keycloak instance? Do I have to build my own ClientResponseFilter
, if so how to handle expired tokens?
Are there any existing implementations / standards I didn't find?
JAX-RS webservice interface:
@Path("/demo")
public interface IDemoService {
@GET
@Path("/test")
String test();
}
Simple Spring Security configuration:
http.cors().and().csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.sessionAuthenticationStrategy(sessionAuthenticationStrategy()).and().authorizeRequests().antMatchers("/**")
.authenticated();
EDIT: new workaround to get initial access- and refresh token from server:
AccessTokenResponse tokens = AuthUtil.getAuthTokens("http://localhost:8180/auth", "share-server", "test", "test", "share-server-service-login");
String accessToken = tokens.getToken();
String refreshToken = tokens.getRefreshToken();
Client doing service calls until the token expires:
URI apiUri = new URI("http://localhost:8080/services/");
RestClientBuilder client = new CxfTypeSafeClientBuilder().baseUri(apiUri).register(new TokenFilter(accessToken, refreshToken));
IDemoService service = client.build(IDemoService.class);
for (int i = 0; i < 200; i++) {
System.out.println("client: " + new Date() + " " + service.test());
Thread.sleep(10000);
}
TokenFilter which works until the access-token expires:
public static class TokenFilter implements ClientRequestFilter, ClientResponseFilter {
private String accessToken;
private String refreshToken;
public TokenFilter(String accessToken, String refreshToken) {
this.accessToken = accessToken;
this.refreshToken = refreshToken;
}
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
if (responseContext.getStatus() == 401 && "invalid_token".equals(responseContext.getStatusInfo().getReasonPhrase())) {
// maybe handle send the refresh token... probalby should be handled earlier using the 'expires' value
}
}
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
if (accessToken != null && !accessToken.isEmpty()) {
requestContext.getHeaders().add(HttpHeaders.AUTHORIZATION, "Bearer" + " " + accessToken);
}
}
}