Java Code Examples for org.keycloak.models.RealmModel#getClientByClientId()

The following examples show how to use org.keycloak.models.RealmModel#getClientByClientId() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FineGrainAdminUnitTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static void setupTokenExchange(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("master");
    ClientModel client = session.realms().getClientByClientId("kcinit", realm);
    if (client != null) {
        return;
    }

    ClientModel kcinit = realm.addClient("kcinit");
    kcinit.setEnabled(true);
    kcinit.addRedirectUri("http://localhost:*");
    kcinit.setPublicClient(false);
    kcinit.setSecret("password");
    kcinit.setDirectAccessGrantsEnabled(true);

    // permission for client to client exchange to "target" client
    ClientModel adminCli = realm.getClientByClientId(ConfigUtil.DEFAULT_CLIENT);
    AdminPermissionManagement management = AdminPermissions.management(session, realm);
    management.clients().setPermissionsEnabled(adminCli, true);
    ClientPolicyRepresentation clientRep = new ClientPolicyRepresentation();
    clientRep.setName("to");
    clientRep.addClient(kcinit.getId());
    ResourceServer server = management.realmResourceServer();
    Policy clientPolicy = management.authz().getStoreFactory().getPolicyStore().create(clientRep, server);
    management.clients().exchangeToPermission(adminCli).addAssociatedPolicy(clientPolicy);
}
 
Example 2
Source File: FineGrainAdminUnitTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void invokeDelete(KeycloakSession session)  {
    RealmModel realm = session.realms().getRealmByName(TEST);
    AdminPermissionManagement management = AdminPermissions.management(session, realm);
    List<Resource> byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer().getId());
    Assert.assertEquals(5, byResourceServer.size());
    RoleModel removedRole = realm.getRole("removedRole");
    realm.removeRole(removedRole);
    ClientModel client = realm.getClientByClientId("removedClient");
    RoleModel removedClientRole = client.getRole("removedClientRole");
    client.removeRole(removedClientRole);
    GroupModel group = KeycloakModelUtils.findGroupByPath(realm, "removedGroup");
    realm.removeGroup(group);
    byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer().getId());
    Assert.assertEquals(2, byResourceServer.size());
    realm.removeClient(client.getId());
    byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer().getId());
    Assert.assertEquals(1, byResourceServer.size());
    management.users().setPermissionsEnabled(false);
    Resource userResource = management.authz().getStoreFactory().getResourceStore().findByName("Users", management.realmResourceServer().getId());
    Assert.assertNull(userResource);
    byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer().getId());
    Assert.assertEquals(0, byResourceServer.size());
}
 
Example 3
Source File: RealmManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void setupBrokerService(RealmModel realm) {
    ClientModel client = realm.getClientByClientId(Constants.BROKER_SERVICE_CLIENT_ID);
    if (client == null) {
        client = KeycloakModelUtils.createClient(realm, Constants.BROKER_SERVICE_CLIENT_ID);
        client.setEnabled(true);
        client.setAlwaysDisplayInConsole(false);
        client.setName("${client_" + Constants.BROKER_SERVICE_CLIENT_ID + "}");
        client.setFullScopeAllowed(false);
        client.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);

        for (String role : Constants.BROKER_SERVICE_ROLES) {
            RoleModel roleModel = client.addRole(role);
            roleModel.setDescription("${role_"+ role.toLowerCase().replaceAll("_", "-") +"}");
        }
    }
}
 
Example 4
Source File: RealmManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void setupAdminConsole(RealmModel realm) {
    ClientModel adminConsole = realm.getClientByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID);
    if (adminConsole == null) adminConsole = KeycloakModelUtils.createClient(realm, Constants.ADMIN_CONSOLE_CLIENT_ID);
    adminConsole.setName("${client_" + Constants.ADMIN_CONSOLE_CLIENT_ID + "}");

    adminConsole.setRootUrl(Constants.AUTH_ADMIN_URL_PROP);
    String baseUrl = "/admin/" + realm.getName() + "/console/";
    adminConsole.setBaseUrl(baseUrl);
    adminConsole.addRedirectUri(baseUrl + "*");
    adminConsole.setWebOrigins(Collections.singleton("+"));

    adminConsole.setEnabled(true);
    adminConsole.setAlwaysDisplayInConsole(false);
    adminConsole.setPublicClient(true);
    adminConsole.setFullScopeAllowed(false);
    adminConsole.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);

    adminConsole.setAttribute(OIDCConfigAttributes.PKCE_CODE_CHALLENGE_METHOD, "S256");
}
 
Example 5
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void createRoleMappings(UserRepresentation userRep, UserModel user, RealmModel realm) {
    if (userRep.getRealmRoles() != null) {
        for (String roleString : userRep.getRealmRoles()) {
            RoleModel role = realm.getRole(roleString.trim());
            if (role == null) {
                role = realm.addRole(roleString.trim());
            }
            user.grantRole(role);
        }
    }
    if (userRep.getClientRoles() != null) {
        for (Map.Entry<String, List<String>> entry : userRep.getClientRoles().entrySet()) {
            ClientModel client = realm.getClientByClientId(entry.getKey());
            if (client == null) {
                throw new RuntimeException("Unable to find client role mappings for client: " + entry.getKey());
            }
            createClientRoleMappings(client, user, entry.getValue());
        }
    }
}
 
Example 6
Source File: RoleLDAPStorageMapper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected RoleContainerModel getTargetRoleContainer(RealmModel realm) {
    boolean realmRolesMapping = config.isRealmRolesMapping();
    if (realmRolesMapping) {
        return realm;
    } else {
        String clientId = config.getClientId();
        if (clientId == null) {
            throw new ModelException("Using client roles mapping is requested, but parameter client.id not found!");
        }
        ClientModel client = realm.getClientByClientId(clientId);
        if (client == null) {
            throw new ModelException("Can't found requested client with clientId: " + clientId);
        }
        return client;
    }
}
 
Example 7
Source File: RealmManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void setupRealmAdminManagement(RealmModel realm) {
    if (realm.getName().equals(Config.getAdminRealm())) { return; } // don't need to do this for master realm

    String realmAdminClientId = getRealmAdminClientId(realm);
    ClientModel realmAdminClient = realm.getClientByClientId(realmAdminClientId);
    if (realmAdminClient == null) {
        realmAdminClient = KeycloakModelUtils.createClient(realm, realmAdminClientId);
        realmAdminClient.setName("${client_" + realmAdminClientId + "}");
    }
    RoleModel adminRole = realmAdminClient.addRole(AdminRoles.REALM_ADMIN);
    adminRole.setDescription("${role_" + AdminRoles.REALM_ADMIN + "}");
    realmAdminClient.setBearerOnly(true);
    realmAdminClient.setFullScopeAllowed(false);
    realmAdminClient.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);

    for (String r : AdminRoles.ALL_REALM_ROLES) {
        addAndSetAdminRole(r, realmAdminClient, adminRole);
    }
    addQueryCompositeRoles(realmAdminClient);
}
 
Example 8
Source File: MigrateTo3_0_0.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void migrateRealm(RealmModel realm) {
    realm.getClients().stream()
            .filter(clientModel -> defaultClients.contains(clientModel.getId()))
            .filter(clientModel -> Objects.isNull(clientModel.getProtocol()))
            .forEach(clientModel -> clientModel.setProtocol("openid-connect"));

    ClientModel client = realm.getClientByClientId(ACCOUNT_MANAGEMENT_CLIENT_ID);
    if (client == null) return;
    RoleModel linkRole = client.getRole(MANAGE_ACCOUNT_LINKS);
    if (linkRole == null) {
        client.addRole(MANAGE_ACCOUNT_LINKS);
    }
    RoleModel manageAccount = client.getRole(MANAGE_ACCOUNT);
    if (manageAccount == null) return;
    RoleModel manageAccountLinks = client.getRole(MANAGE_ACCOUNT_LINKS);
    manageAccount.addCompositeRole(manageAccountLinks);
}
 
Example 9
Source File: RealmsResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a temporary redirect to the client url configured for the given {@code clientId} in the given {@code realmName}.
 * <p>
 * This allows a client to refer to other clients just by their client id in URLs, will then redirect users to the actual client url.
 * The client url is derived according to the rules of the base url in the client configuration.
 * </p>
 *
 * @param realmName
 * @param clientId
 * @return
 * @since 2.0
 */
@GET
@Path("{realm}/clients/{client_id}/redirect")
public Response getRedirect(final @PathParam("realm") String realmName, final @PathParam("client_id") String clientId) {

    RealmModel realm = init(realmName);

    if (realm == null) {
        return null;
    }

    ClientModel client = realm.getClientByClientId(clientId);

    if (client == null) {
        return null;
    }

    if (client.getRootUrl() == null && client.getBaseUrl() == null) {
        return null;
    }


    URI targetUri;
    if (client.getRootUrl() != null && (client.getBaseUrl() == null || client.getBaseUrl().isEmpty())) {
        targetUri = KeycloakUriBuilder.fromUri(client.getRootUrl()).build();
    } else {
        targetUri = KeycloakUriBuilder.fromUri(ResolveRelative.resolveRelativeUri(session, client.getRootUrl(), client.getBaseUrl())).build();
    }

    return Response.seeOther(targetUri).build();
}
 
Example 10
Source File: MigrateTo9_0_0.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void addAccountApiRoles(RealmModel realm) {
    ClientModel accountClient = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
    RoleModel viewAppRole = accountClient.addRole(AccountRoles.VIEW_APPLICATIONS);
    viewAppRole.setDescription("${role_" + AccountRoles.VIEW_APPLICATIONS + "}");
    LOG.debugf("Added the role %s to the '%s' client.", AccountRoles.VIEW_APPLICATIONS, Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
    RoleModel viewConsentRole = accountClient.addRole(AccountRoles.VIEW_CONSENT);
    viewConsentRole.setDescription("${role_" + AccountRoles.VIEW_CONSENT + "}");
    LOG.debugf("Added the role %s to the '%s' client.", AccountRoles.VIEW_CONSENT, Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
    RoleModel manageConsentRole = accountClient.addRole(AccountRoles.MANAGE_CONSENT);
    manageConsentRole.setDescription("${role_" + AccountRoles.MANAGE_CONSENT + "}");
    LOG.debugf("Added the role %s to the '%s' client.", AccountRoles.MANAGE_CONSENT, Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
    manageConsentRole.addCompositeRole(viewConsentRole);
    LOG.debugf("Added the %s role as a composite role to %s", AccountRoles.VIEW_CONSENT, AccountRoles.MANAGE_CONSENT);
}
 
Example 11
Source File: BrokerRunOnServerUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
static RunOnServer grantReadTokenRole(String username) {
    return session -> {
        RealmModel realm = session.getContext().getRealm();
        ClientModel brokerClient = realm.getClientByClientId(Constants.BROKER_SERVICE_CLIENT_ID);
        RoleModel readTokenRole = brokerClient.getRole(Constants.READ_TOKEN_ROLE);
        UserModel user = session.users().getUserByUsername(username, realm);
        user.grantRole(readTokenRole);
    };
}
 
Example 12
Source File: TestCacheUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void cacheRealmWithEverything(KeycloakSession session, String realmName) {
    RealmModel realm  = session.realms().getRealmByName(realmName);

    for (ClientModel client : realm.getClients()) {
        realm.getClientById(client.getId());
        realm.getClientByClientId(client.getClientId());

        cacheRoles(session, realm, client);
    }

    cacheRoles(session, realm, realm);

    for (GroupModel group : realm.getTopLevelGroups()) {
        cacheGroupRecursive(realm, group);
    }

    for (ClientScopeModel clientScope : realm.getClientScopes()) {
        realm.getClientScopeById(clientScope.getId());
    }

    for (UserModel user : session.users().getUsers(realm)) {
        session.users().getUserById(user.getId(), realm);
        if (user.getEmail() != null) {
            session.users().getUserByEmail(user.getEmail(), realm);
        }
        session.users().getUserByUsername(user.getUsername(), realm);

        session.users().getConsents(realm, user.getId());

        for (FederatedIdentityModel fedIdentity : session.users().getFederatedIdentities(user, realm)) {
            session.users().getUserByFederatedIdentity(fedIdentity, realm);
        }
    }
}
 
Example 13
Source File: UserCommands.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Set<RoleModel> findRoles(RealmModel realm, String rolesList) {
    Set<RoleModel> result = new HashSet<>();

    String[] roles = rolesList.split(",");
    for (String roleName : roles) {
        roleName = roleName.trim();
        RoleModel role;
        if (roleName.contains("/")) {
            String[] spl = roleName.split("/");
            ClientModel client = realm.getClientByClientId(spl[0]);
            if (client == null) {
                log.errorf("Client not found: %s", spl[0]);
                throw new HandledException();
            }
            role = client.getRole(spl[1]);
        } else {
            role = realm.getRole(roleName);
        }

        if (role == null) {
            log.errorf("Role not found: %s", roleName);
            throw new HandledException();
        }

        result.add(role);
    }

    return result;
}
 
Example 14
Source File: RealmManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void setupMasterAdminManagement(RealmModel realm) {
    // Need to refresh masterApp for current realm
    String adminRealmId = Config.getAdminRealm();
    RealmModel adminRealm = model.getRealm(adminRealmId);
    ClientModel masterApp = adminRealm.getClientByClientId(KeycloakModelUtils.getMasterRealmAdminApplicationClientId(realm.getName()));
    if (masterApp != null) {
        realm.setMasterAdminClient(masterApp);
    }  else {
        createMasterAdminManagement(realm);
    }
}
 
Example 15
Source File: RealmManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void setupAdminConsoleLocaleMapper(RealmModel realm) {
    ClientModel adminConsole = realm.getClientByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID);
    ProtocolMapperModel localeMapper = adminConsole.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, OIDCLoginProtocolFactory.LOCALE);

    if (localeMapper == null) {
        localeMapper = ProtocolMapperUtils.findLocaleMapper(session);
        if (localeMapper != null) {
            adminConsole.addProtocolMapper(localeMapper);
        }
    }
}
 
Example 16
Source File: TokenManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the token is valid. Intended usage is for token introspection endpoints as the session last refresh
 * is updated if the token was valid. This is used to keep the session alive when long lived tokens are used.
 *
 * @param session
 * @param realm
 * @param token
 * @return
 * @throws OAuthErrorException
 */
public boolean checkTokenValidForIntrospection(KeycloakSession session, RealmModel realm, AccessToken token) throws OAuthErrorException {
    ClientModel client = realm.getClientByClientId(token.getIssuedFor());
    if (client == null || !client.isEnabled()) {
        return false;
    }

    try {
        TokenVerifier.createWithoutSignature(token)
                .withChecks(NotBeforeCheck.forModel(client), TokenVerifier.IS_ACTIVE)
                .verify();
    } catch (VerificationException e) {
        return false;
    }

    boolean valid = false;

    UserSessionModel userSession = new UserSessionCrossDCManager(session).getUserSessionWithClient(realm, token.getSessionState(), false, client.getId());

    if (AuthenticationManager.isSessionValid(realm, userSession)) {
        valid = isUserValid(session, realm, token, userSession);
    } else {
        userSession = new UserSessionCrossDCManager(session).getUserSessionWithClient(realm, token.getSessionState(), true, client.getId());
        if (AuthenticationManager.isOfflineSessionValid(realm, userSession)) {
            valid = isUserValid(session, realm, token, userSession);
        }
    }

    if (valid) {
        userSession.setLastSessionRefresh(Time.currentTime());
    }

    return valid;
}
 
Example 17
Source File: AccountLoader.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public Object getAccountService(KeycloakSession session, EventBuilder event) {
    RealmModel realm = session.getContext().getRealm();

    ClientModel client = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
    if (client == null || !client.isEnabled()) {
        logger.debug("account management not enabled");
        throw new NotFoundException("account management not enabled");
    }

    HttpRequest request = session.getContext().getContextObject(HttpRequest.class);
    HttpHeaders headers = session.getContext().getRequestHeaders();
    MediaType content = headers.getMediaType();
    List<MediaType> accepts = headers.getAcceptableMediaTypes();

    Theme theme = getTheme(session);
    boolean deprecatedAccount = isDeprecatedFormsAccountConsole(theme);
    UriInfo uriInfo = session.getContext().getUri();

    if (request.getHttpMethod().equals(HttpMethod.OPTIONS)) {
        return new CorsPreflightService(request);
    } else if ((accepts.contains(MediaType.APPLICATION_JSON_TYPE) || MediaType.APPLICATION_JSON_TYPE.equals(content)) && !uriInfo.getPath().endsWith("keycloak.json")) {
        AuthenticationManager.AuthResult authResult = new AppAuthManager().authenticateBearerToken(session);
        if (authResult == null) {
            throw new NotAuthorizedException("Bearer token required");
        }

        if (authResult.getUser().getServiceAccountClientLink() != null) {
            throw new NotAuthorizedException("Service accounts are not allowed to access this service");
        }

        Auth auth = new Auth(session.getContext().getRealm(), authResult.getToken(), authResult.getUser(), client, authResult.getSession(), false);
        AccountRestService accountRestService = new AccountRestService(session, auth, client, event);
        ResteasyProviderFactory.getInstance().injectProperties(accountRestService);
        accountRestService.init();
        return accountRestService;
    } else {
        if (deprecatedAccount) {
            AccountFormService accountFormService = new AccountFormService(realm, client, event);
            ResteasyProviderFactory.getInstance().injectProperties(accountFormService);
            accountFormService.init();
            return accountFormService;
        } else {
            AccountConsole console = new AccountConsole(realm, client, theme);
            ResteasyProviderFactory.getInstance().injectProperties(console);
            console.init();
            return console;
        }
    }
}
 
Example 18
Source File: ClientsPartialImport.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public boolean exists(RealmModel realm, KeycloakSession session, ClientRepresentation clientRep) {
    return realm.getClientByClientId(getName(clientRep)) != null;
}
 
Example 19
Source File: ClientTokenExchangeTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static void setupRealm(KeycloakSession session) {
    addDirectExchanger(session);

    RealmModel realm = session.realms().getRealmByName(TEST);
    RoleModel exampleRole = realm.getRole("example");

    AdminPermissionManagement management = AdminPermissions.management(session, realm);
    ClientModel target = realm.getClientByClientId("target");
    assertNotNull(target);

    RoleModel impersonateRole = management.getRealmManagementClient().getRole(ImpersonationConstants.IMPERSONATION_ROLE);

    ClientModel clientExchanger = realm.addClient("client-exchanger");
    clientExchanger.setClientId("client-exchanger");
    clientExchanger.setPublicClient(false);
    clientExchanger.setDirectAccessGrantsEnabled(true);
    clientExchanger.setEnabled(true);
    clientExchanger.setSecret("secret");
    clientExchanger.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    clientExchanger.setFullScopeAllowed(false);
    clientExchanger.addScopeMapping(impersonateRole);
    clientExchanger.addProtocolMapper(UserSessionNoteMapper.createUserSessionNoteMapper(IMPERSONATOR_ID));
    clientExchanger.addProtocolMapper(UserSessionNoteMapper.createUserSessionNoteMapper(IMPERSONATOR_USERNAME));

    ClientModel illegal = realm.addClient("illegal");
    illegal.setClientId("illegal");
    illegal.setPublicClient(false);
    illegal.setDirectAccessGrantsEnabled(true);
    illegal.setEnabled(true);
    illegal.setSecret("secret");
    illegal.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    illegal.setFullScopeAllowed(false);

    ClientModel legal = realm.addClient("legal");
    legal.setClientId("legal");
    legal.setPublicClient(false);
    legal.setDirectAccessGrantsEnabled(true);
    legal.setEnabled(true);
    legal.setSecret("secret");
    legal.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    legal.setFullScopeAllowed(false);

    ClientModel directLegal = realm.addClient("direct-legal");
    directLegal.setClientId("direct-legal");
    directLegal.setPublicClient(false);
    directLegal.setDirectAccessGrantsEnabled(true);
    directLegal.setEnabled(true);
    directLegal.setSecret("secret");
    directLegal.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    directLegal.setFullScopeAllowed(false);

    ClientModel directPublic = realm.addClient("direct-public");
    directPublic.setClientId("direct-public");
    directPublic.setPublicClient(true);
    directPublic.setDirectAccessGrantsEnabled(true);
    directPublic.setEnabled(true);
    directPublic.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    directPublic.setFullScopeAllowed(false);

    ClientModel directNoSecret = realm.addClient("direct-no-secret");
    directNoSecret.setClientId("direct-no-secret");
    directNoSecret.setPublicClient(false);
    directNoSecret.setDirectAccessGrantsEnabled(true);
    directNoSecret.setEnabled(true);
    directNoSecret.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    directNoSecret.setFullScopeAllowed(false);

    // permission for client to client exchange to "target" client
    ClientPolicyRepresentation clientRep = new ClientPolicyRepresentation();
    clientRep.setName("to");
    clientRep.addClient(clientExchanger.getId());
    clientRep.addClient(legal.getId());
    clientRep.addClient(directLegal.getId());

    ResourceServer server = management.realmResourceServer();
    Policy clientPolicy = management.authz().getStoreFactory().getPolicyStore().create(clientRep, server);
    management.clients().exchangeToPermission(target).addAssociatedPolicy(clientPolicy);

    // permission for user impersonation for a client

    ClientPolicyRepresentation clientImpersonateRep = new ClientPolicyRepresentation();
    clientImpersonateRep.setName("clientImpersonators");
    clientImpersonateRep.addClient(directLegal.getId());
    clientImpersonateRep.addClient(directPublic.getId());
    clientImpersonateRep.addClient(directNoSecret.getId());
    server = management.realmResourceServer();
    Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(clientImpersonateRep, server);
    management.users().setPermissionsEnabled(true);
    management.users().adminImpersonatingPermission().addAssociatedPolicy(clientImpersonatePolicy);
    management.users().adminImpersonatingPermission().setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);

    UserModel user = session.users().addUser(realm, "user");
    user.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password("password"));
    user.grantRole(exampleRole);
    user.grantRole(impersonateRole);

    UserModel bad = session.users().addUser(realm, "bad-impersonator");
    bad.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, bad, UserCredentialModel.password("password"));
}
 
Example 20
Source File: AuthorizationTokenService.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private AuthorizationResponse createAuthorizationResponse(KeycloakIdentity identity, Collection<Permission> entitlements, KeycloakAuthorizationRequest request, ClientModel targetClient) {
    KeycloakSession keycloakSession = request.getKeycloakSession();
    AccessToken accessToken = identity.getAccessToken();
    RealmModel realm = request.getRealm();
    UserSessionProvider sessions = keycloakSession.sessions();
    UserSessionModel userSessionModel = sessions.getUserSession(realm, accessToken.getSessionState());

    if (userSessionModel == null) {
        userSessionModel = sessions.getOfflineUserSession(realm, accessToken.getSessionState());
    }

    ClientModel client = realm.getClientByClientId(accessToken.getIssuedFor());
    AuthenticatedClientSessionModel clientSession = userSessionModel.getAuthenticatedClientSessionByClient(targetClient.getId());
    ClientSessionContext clientSessionCtx;

    if (clientSession == null) {
        RootAuthenticationSessionModel rootAuthSession = keycloakSession.authenticationSessions().getRootAuthenticationSession(realm, userSessionModel.getId());

        if (rootAuthSession == null) {
            if (userSessionModel.getUser().getServiceAccountClientLink() == null) {
                rootAuthSession = keycloakSession.authenticationSessions().createRootAuthenticationSession(userSessionModel.getId(), realm);
            } else {
                // if the user session is associated with a service account
                rootAuthSession = new AuthenticationSessionManager(keycloakSession).createAuthenticationSession(realm, false);
            }
        }

        AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(targetClient);

        authSession.setAuthenticatedUser(userSessionModel.getUser());
        authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(keycloakSession.getContext().getUri().getBaseUri(), realm.getName()));

        AuthenticationManager.setClientScopesInSession(authSession);
        clientSessionCtx = TokenManager.attachAuthenticationSession(keycloakSession, userSessionModel, authSession);
    } else {
        clientSessionCtx = DefaultClientSessionContext.fromClientSessionScopeParameter(clientSession, keycloakSession);
    }

    TokenManager tokenManager = request.getTokenManager();
    EventBuilder event = request.getEvent();
    AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, event, keycloakSession, userSessionModel, clientSessionCtx)
            .generateAccessToken()
            .generateRefreshToken();
    AccessToken rpt = responseBuilder.getAccessToken();
    Authorization authorization = new Authorization();

    authorization.setPermissions(entitlements);

    rpt.setAuthorization(authorization);

    RefreshToken refreshToken = responseBuilder.getRefreshToken();

    refreshToken.issuedFor(client.getClientId());
    refreshToken.setAuthorization(authorization);

    if (!rpt.hasAudience(targetClient.getClientId())) {
        rpt.audience(targetClient.getClientId());
    }

    return new AuthorizationResponse(responseBuilder.build(), isUpgraded(request, authorization));
}