Technical Details:
Keycloak Version: 12.0.2
Java Version: 1.8
Java Admin Client: 12.0.2
Keycloak Spring boot starter
Description
I have a Spring Boot application where internal staff can create and modify Keycloak users, using its official java dependency. This application should also contain an impersonation function.
I tried impersonating with the Java Admin Client, the impersonate function returns a map, which contains the Boolean “sameRealm” and the redirect URL to the account page of Keycloak. With these 2 values I can’t access the session of the impersonated User nor can I really use these attributes for something else.
Afterwards I tried the impersonate function of the Keycloak Rest API, the API returned some Cookies in the header unfortunately I can’t seem to figure out how to use these cookies, but I tried creating these cookies and set them but unfortunately it didn’t work.
Lastly, I tried a token exchange to receive a valid access token and fortunately the function works.
token-exchange function
Keycloak keycloakService = KeycloakBuilder.builder()
.serverUrl(serverUrl)
.realm(realm)
.clientId(clientId)
.grantType(OAuth2Constants.CLIENT_CREDENTIALS)
.clientSecret(clientSecret)
.build();
BasicCookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
HttpUriRequest reqBuild = RequestBuilder.post()
.setUri(serverUrl + "/realms/intern/protocol/openid-connect/token")
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addParameter("client_id", "example")
.addParameter("client_secret", "example") //
.addParameter("grant_type", "urn:ietf:params:oauth:grant-type:token-exchange")
.addParameter("subject_token", keycloakService.tokenManager().getAccessTokenString())
.addParameter("requested_token_type", "urn:ietf:params:oauth:token-type:access_token")
.addParameter("requested_subject", userId)
.addParameter("audience", "target-client")
.build();
HttpResponse res = httpClient.execute(reqBuild);
String resBody = EntityUtils.toString(res.getEntity());
System.out.println(resBody);
With the above code I receive a valid access-token from Keycloak. But unfortunately, I don’t know how I can use this token to complete the Impersonation process.
The setup is as following: id.example.com provides the Spring Boot Application, sso.id.example.com runs KeyCloak instance. For my understanding, I should create a cookie for sso.id.example.com
If someone has another solution on how I can Impersonate a user and then acquire the associated session. I would appreciate the help.