Impersonation with Keycloak[version: 21.] not working [Springboot version: 2.6.6]

125 Views Asked by At

So I have been trying to implement the Impersonate-Function using the Keycloak Admin Client: impersonate() function called from UserResource.

`
@POST
@Path("impersonation")
@Produces(MediaType.APPLICATION_JSON)
Map<String, Object> impersonate();
}`

In my KeycloakService, this is how I call this function:

`
    ...
    import org.keycloak.admin.client.resource.UserResource;
    import org.keycloak.admin.client.Keycloak;
    ...
    public class KeycloakService {
        ...
    private Keycloak keycloak;
        ...
        public Map<String, Object> impersonateUser(String userId) {
            UserResource userResource = keycloak.realm(realm).users().get(userId);
            Map<String, Object> impersonateResponse = userResource.impersonate();
            return impersonateResponse;
    }
`

Calling this function in my AdminController as follows:

`
    @RolesAllowed("*appname*:superadmin")
    @PostMapping(value ="/*URLpath*" , params = "impersonation")
    public String impersonateUser(@ModelAttribute("editUserModel") UserModel userModel){
        Map<String, Object> impersonateMap = keycloakService.impersonateUser(userModel.getId()); 
        return "redirect:" + impersonateMap.get("redirect");
    }
`

After triggering the function, I get redirected to the sso url in keycloak (just as I am declaring it on the return in AdminController.impersonateUser). So far so good... the issue is, that I'm not logged in with the User, that I am passing the UserID of, but it's just me that's logged in. When I open the Application-Memory and check the Cookies, the following fields are set:

KEYCLOAK_IDENTITY_LEGACY - not sure what that's supposed to be KEYCLOAK_IDENTITY - same KEYCLOAK_SESSION_LEGACY - realm/myID/auth_session_id KEYCLOAK_SESSION - realm/myID/auth_session_id KEYCLOAK_LOCALE - localeAttribute AUTH_SESSION_ID - This should be my auth-token AUTH_SESSION_LEGACY - it's the same as above

I checked to see whether the KEYCLOAK_IDENTITY value matches the Users's ID, and found out that it is not matching. Why is it not matching?? This is also probably the reason why I'm not redirected as the impersonated user. Could someone help me out? This is the first time I am dealing with SSO-Solutions and all this Cookie, AuthenticationTokens ... is very confusing to me.

The preferred output, would be to be redirected onto my app's landing page, and also be logged in as the "ToBeImpersonatedUser".

KeycloakVersion: KeyCloakAdminClient 21.1.1 SpringBootVersion:2.6.6 Java: 11

Thanks in advance and happy Christmas-Coding to all the Holiday-Coders :).

0

There are 0 best solutions below