I have the following code to refresh my access token:
@PostMapping(value = "/auth/realms/{realm-name}/protocol/openid-connect/token/refresh", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public AccessTokenResponse refreshToken(
@PathVariable("realm-name") String realmName,
RefreshAccessTokenDTO dto) {
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("grant_type", dto.getGrantType());
body.add("client_id", dto.getClientId());
body.add("client_secret", dto.getClientSecret());
body.add("refresh_token", dto.getRefreshToken());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<?> httpEntity = new HttpEntity<>(body, headers);
String url = String.format("http://localhost:8180/auth/realms/%s/protocol/openid-connect/token", realmName);
ResponseEntity<AccessTokenResponse> response = new RestTemplate().exchange(url, HttpMethod.POST, httpEntity, AccessTokenResponse.class);
return response.getBody();
}
Works great, but I would like to use the admin client like I do when asking for access token with username & password:
@PostMapping(value = "/auth/realms/{realm-name}/protocol/openid-connect/token", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public AccessTokenResponse getToken(@PathVariable("realm-name") String realmName, OpenIdConnectTokenRequest dto) {
Keycloak kc = keycloakFactory.getKeycloak("http://localhost:8180/auth", dto, realmName);
TokenManager tokenManager = kc.tokenManager();
return tokenManager.getAccessToken();
}
private Keycloak getKeycloak(String authServerUrl, OpenIdConnectTokenRequest dto, String realmName) {
return KeycloakBuilder.builder()
.serverUrl(authServerUrl)
.realm(realmName)
.username(dto.getUsername())
.password(dto.getPassword())
.clientId(dto.getClientId())
.clientSecret(dto.getClientSecret())
.resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build())
.build();
}
Is it possible to refresh the access token with admin client?
If yes, how to build a Keycloak instance to make it work?