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

The following examples show how to use org.keycloak.models.RealmModel#getClientById() . 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: ClientPolicyProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void evaluate(Evaluation evaluation) {
    ClientPolicyRepresentation representation = representationFunction.apply(evaluation.getPolicy(), evaluation.getAuthorizationProvider());
    AuthorizationProvider authorizationProvider = evaluation.getAuthorizationProvider();
    RealmModel realm = authorizationProvider.getKeycloakSession().getContext().getRealm();
    EvaluationContext context = evaluation.getContext();

    for (String client : representation.getClients()) {
        ClientModel clientModel = realm.getClientById(client);

        if (context.getAttributes().containsValue("kc.client.id", clientModel.getClientId())) {
            evaluation.grant();
            return;
        }
    }
}
 
Example 2
Source File: ProtectionService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private ResourceServer getResourceServer(KeycloakIdentity identity) {
    String clientId = identity.getAccessToken().getIssuedFor();
    RealmModel realm = authorization.getKeycloakSession().getContext().getRealm();
    ClientModel clientModel = realm.getClientByClientId(clientId);

    if (clientModel == null) {
        clientModel = realm.getClientById(clientId);

        if (clientModel == null) {
            throw new ErrorResponseException("invalid_clientId", "Client application with id [" + clientId + "] does not exist in realm [" + realm.getName() + "]", Status.BAD_REQUEST);
        }
    }

    ResourceServer resourceServer = this.authorization.getStoreFactory().getResourceServerStore().findById(clientModel.getId());

    if (resourceServer == null) {
        throw new ErrorResponseException("invalid_clientId", "Client application [" + clientModel.getClientId() + "] is not registered as a resource server.", Status.FORBIDDEN);
    }

    return resourceServer;
}
 
Example 3
Source File: KeycloakModelUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Lookup clientScope OR client by id. Method is useful if you know just ID, but you don't know
 * if underlying model is clientScope or client
 */
public static ClientScopeModel findClientScopeById(RealmModel realm, ClientModel client, String clientScopeId) {
    ClientScopeModel clientScope = realm.getClientScopeById(clientScopeId);

    if (clientScope ==  null) {
        // as fallback we try to resolve dynamic scopes
        clientScope = client.getDynamicClientScope(clientScopeId);
    }

    if (clientScope != null) {
        return clientScope;
    } else {
        return realm.getClientById(clientScopeId);
    }
}
 
Example 4
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 5
Source File: JpaUserSessionPersisterProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private PersistentAuthenticatedClientSessionAdapter toAdapter(RealmModel realm, PersistentUserSessionAdapter userSession, PersistentClientSessionEntity entity) {
    String clientId = entity.getClientId();
    if (!entity.getExternalClientId().equals("local")) {
        clientId = new StorageId(entity.getClientId(), entity.getExternalClientId()).getId();
    }
    ClientModel client = realm.getClientById(clientId);

    PersistentClientSessionModel model = new PersistentClientSessionModel();
    model.setClientId(clientId);
    model.setUserSessionId(userSession.getId());
    model.setUserId(userSession.getUserId());
    model.setTimestamp(entity.getTimestamp());
    model.setData(entity.getData());
    return new PersistentAuthenticatedClientSessionAdapter(model, realm, client, userSession);
}
 
Example 6
Source File: JpaUserProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private UserConsentModel toConsentModel(RealmModel realm, UserConsentEntity entity) {
    if (entity == null) {
        return null;
    }

    StorageId clientStorageId = null;
    if ( entity.getClientId() == null) {
        clientStorageId = new StorageId(entity.getClientStorageProvider(), entity.getExternalClientId());
    } else {
        clientStorageId = new StorageId(entity.getClientId());
    }

    ClientModel client = realm.getClientById(clientStorageId.getId());
    if (client == null) {
        throw new ModelException("Client with id " + clientStorageId.getId() + " is not available");
    }
    UserConsentModel model = new UserConsentModel(client);
    model.setCreatedDate(entity.getCreatedDate());
    model.setLastUpdatedDate(entity.getLastUpdatedDate());

    Collection<UserConsentClientScopeEntity> grantedClientScopeEntities = entity.getGrantedClientScopes();
    if (grantedClientScopeEntities != null) {
        for (UserConsentClientScopeEntity grantedClientScope : grantedClientScopeEntities) {
            ClientScopeModel grantedClientScopeModel = KeycloakModelUtils.findClientScopeById(realm, client, grantedClientScope.getScopeId());
            if (grantedClientScopeModel != null) {
                model.addGrantedClientScope(grantedClientScopeModel);
            }
        }
    }

    return model;
}
 
Example 7
Source File: JpaUserFederatedStorageProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private UserConsentModel toConsentModel(RealmModel realm, FederatedUserConsentEntity entity) {
    if (entity == null) {
        return null;
    }

    StorageId clientStorageId = null;
    if ( entity.getClientId() == null) {
        clientStorageId = new StorageId(entity.getClientStorageProvider(), entity.getExternalClientId());
    } else {
        clientStorageId = new StorageId(entity.getClientId());
    }

    ClientModel client = realm.getClientById(clientStorageId.getId());
    UserConsentModel model = new UserConsentModel(client);
    model.setCreatedDate(entity.getCreatedDate());
    model.setLastUpdatedDate(entity.getLastUpdatedDate());

    Collection<FederatedUserConsentClientScopeEntity> grantedClientScopeEntities = entity.getGrantedClientScopes();
    if (grantedClientScopeEntities != null) {
        for (FederatedUserConsentClientScopeEntity grantedClientScope : grantedClientScopeEntities) {
            ClientScopeModel grantedClientScopeModel = realm.getClientScopeById(grantedClientScope.getScopeId());
            if (grantedClientScopeModel != null) {
                model.addGrantedClientScope(grantedClientScopeModel);
            }
        }
    }

    return model;
}
 
Example 8
Source File: RolePolicyProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private boolean hasRole(Identity identity, RoleModel role, RealmModel realm) {
    String roleName = role.getName();
    if (role.isClientRole()) {
        ClientModel clientModel = realm.getClientById(role.getContainerId());
        return identity.hasClientRole(clientModel.getClientId(), roleName);
    }
    return identity.hasRealmRole(roleName);
}
 
Example 9
Source File: ClientPolicyProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void updateClients(Policy policy, Set<String> clients, AuthorizationProvider authorization) {
    RealmModel realm = authorization.getRealm();

    if (clients == null || clients.isEmpty()) {
        throw new RuntimeException("No client provided.");
    }

    Set<String> updatedClients = new HashSet<>();

    for (String id : clients) {
        ClientModel client = realm.getClientByClientId(id);

        if (client == null) {
            client = realm.getClientById(id);
        }

        if (client == null) {
            throw new RuntimeException("Error while updating policy [" + policy.getName()  + "]. Client [" + id + "] could not be found.");
        }

        updatedClients.add(client.getId());
    }

    try {
        policy.putConfig("clients", JsonSerialization.writeValueAsString(updatedClients));
    } catch (IOException cause) {
        throw new RuntimeException("Failed to serialize clients", cause);
    }
}
 
Example 10
Source File: UserSessionManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public Set<ClientModel> findClientsWithOfflineToken(RealmModel realm, UserModel user) {
    List<UserSessionModel> userSessions = kcSession.sessions().getOfflineUserSessions(realm, user);
    Set<ClientModel> clients = new HashSet<>();
    for (UserSessionModel userSession : userSessions) {
        Set<String> clientIds = userSession.getAuthenticatedClientSessions().keySet();
        for (String clientUUID : clientIds) {
            ClientModel client = realm.getClientById(clientUUID);
            clients.add(client);
        }
    }
    return clients;
}
 
Example 11
Source File: ProtectionService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private AdminEventBuilder createAdminEventBuilder(KeycloakIdentity identity, ResourceServer resourceServer) {
    RealmModel realm = authorization.getRealm();
    ClientModel client = realm.getClientById(resourceServer.getId());
    KeycloakSession keycloakSession = authorization.getKeycloakSession();
    UserModel serviceAccount = keycloakSession.users().getServiceAccount(client);
    AdminEventBuilder adminEvent = new AdminEventBuilder(realm, new AdminAuth(realm, identity.getAccessToken(), serviceAccount, client), keycloakSession, clientConnection);
    return adminEvent.realm(realm).authClient(client).authUser(serviceAccount);
}
 
Example 12
Source File: ProtectionService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private KeycloakIdentity createIdentity(boolean checkProtectionScope) {
    KeycloakIdentity identity = new KeycloakIdentity(this.authorization.getKeycloakSession());
    ResourceServer resourceServer = getResourceServer(identity);
    KeycloakSession keycloakSession = authorization.getKeycloakSession();
    RealmModel realm = keycloakSession.getContext().getRealm();
    ClientModel client = realm.getClientById(resourceServer.getId());

    if (checkProtectionScope) {
        if (!identity.hasClientRole(client.getClientId(), "uma_protection")) {
            throw new ErrorResponseException(OAuthErrorException.INVALID_SCOPE, "Requires uma_protection scope.", Status.FORBIDDEN);
        }
    }

    return identity;
}
 
Example 13
Source File: AuthorizationBean.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public ResourceBean(Resource resource) {
    RealmModel realm = authorization.getRealm();
    resourceServer = new ResourceServerBean(realm.getClientById(resource.getResourceServer().getId()));
    this.resource = resource;
    owner = authorization.getKeycloakSession().users().getUserById(resource.getOwner(), realm);
}
 
Example 14
Source File: IdpVerifyAccountLinkActionTokenHandler.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public Response handleToken(IdpVerifyAccountLinkActionToken token, ActionTokenContext<IdpVerifyAccountLinkActionToken> tokenContext) {
    UserModel user = tokenContext.getAuthenticationSession().getAuthenticatedUser();
    EventBuilder event = tokenContext.getEvent();
    final UriInfo uriInfo = tokenContext.getUriInfo();
    final RealmModel realm = tokenContext.getRealm();
    final KeycloakSession session = tokenContext.getSession();

    event.event(EventType.IDENTITY_PROVIDER_LINK_ACCOUNT)
      .detail(Details.EMAIL, user.getEmail())
      .detail(Details.IDENTITY_PROVIDER, token.getIdentityProviderAlias())
      .detail(Details.IDENTITY_PROVIDER_USERNAME, token.getIdentityProviderUsername())
      .success();

    AuthenticationSessionModel authSession = tokenContext.getAuthenticationSession();
    if (tokenContext.isAuthenticationSessionFresh()) {
        token.setOriginalCompoundAuthenticationSessionId(token.getCompoundAuthenticationSessionId());

        String authSessionEncodedId = AuthenticationSessionCompoundId.fromAuthSession(authSession).getEncodedId();
        token.setCompoundAuthenticationSessionId(authSessionEncodedId);
        UriBuilder builder = Urls.actionTokenBuilder(uriInfo.getBaseUri(), token.serialize(session, realm, uriInfo),
                authSession.getClient().getClientId(), authSession.getTabId());
        String confirmUri = builder.build(realm.getName()).toString();

        return session.getProvider(LoginFormsProvider.class)
                .setAuthenticationSession(authSession)
                .setSuccess(Messages.CONFIRM_ACCOUNT_LINKING, token.getIdentityProviderUsername(), token.getIdentityProviderAlias())
                .setAttribute(Constants.TEMPLATE_ATTR_ACTION_URI, confirmUri)
                .createInfoPage();
    }

    // verify user email as we know it is valid as this entry point would never have gotten here.
    user.setEmailVerified(true);

    if (token.getOriginalCompoundAuthenticationSessionId() != null) {
        AuthenticationSessionManager asm = new AuthenticationSessionManager(session);
        asm.removeAuthenticationSession(realm, authSession, true);

        AuthenticationSessionCompoundId compoundId = AuthenticationSessionCompoundId.encoded(token.getOriginalCompoundAuthenticationSessionId());
        ClientModel originalClient = realm.getClientById(compoundId.getClientUUID());
        authSession = asm.getAuthenticationSessionByIdAndClient(realm, compoundId.getRootSessionId(), originalClient, compoundId.getTabId());

        if (authSession != null) {
            authSession.setAuthNote(IdpEmailVerificationAuthenticator.VERIFY_ACCOUNT_IDP_USERNAME, token.getIdentityProviderUsername());
        } else {

            session.authenticationSessions().updateNonlocalSessionAuthNotes(
                    compoundId,
              Collections.singletonMap(IdpEmailVerificationAuthenticator.VERIFY_ACCOUNT_IDP_USERNAME, token.getIdentityProviderUsername())
            );
        }

        return session.getProvider(LoginFormsProvider.class)
                .setAuthenticationSession(authSession)
                .setSuccess(Messages.IDENTITY_PROVIDER_LINK_SUCCESS, token.getIdentityProviderAlias(), token.getIdentityProviderUsername())
                .setAttribute(Constants.SKIP_LINK, true)
                .createInfoPage();
    }

    authSession.setAuthNote(IdpEmailVerificationAuthenticator.VERIFY_ACCOUNT_IDP_USERNAME, token.getIdentityProviderUsername());

    return tokenContext.brokerFlow(null, null, authSession.getAuthNote(AuthenticationProcessor.CURRENT_FLOW_PATH));
}