Java Code Examples for org.keycloak.models.ClientModel#getClientId()

The following examples show how to use org.keycloak.models.ClientModel#getClientId() . 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: AbstractIdentityProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected String getLinkingUrl(UriInfo uriInfo, ClientModel authorizedClient, UserSessionModel tokenUserSession) {
    String provider = getConfig().getAlias();
    String clientId = authorizedClient.getClientId();
    String nonce = UUID.randomUUID().toString();
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    String input = nonce + tokenUserSession.getId() + clientId + provider;
    byte[] check = md.digest(input.getBytes(StandardCharsets.UTF_8));
    String hash = Base64Url.encode(check);
    return KeycloakUriBuilder.fromUri(uriInfo.getBaseUri())
            .path("/realms/{realm}/broker/{provider}/link")
            .queryParam("nonce", nonce)
            .queryParam("hash", hash)
            .queryParam("client_id", clientId)
            .build(authorizedClient.getRealm().getName(), provider)
            .toString();
}
 
Example 2
Source File: JpaUserProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public UserModel getServiceAccount(ClientModel client) {
    TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserByServiceAccount", UserEntity.class);
    query.setParameter("realmId", client.getRealm().getId());
    query.setParameter("clientInternalId", client.getId());
    List<UserEntity> results = query.getResultList();
    if (results.isEmpty()) {
        return null;
    } else if (results.size() > 1) {
        throw new IllegalStateException("More service account linked users found for client=" + client.getClientId() +
                ", results=" + results);
    } else {
        UserEntity user = results.get(0);
        return new UserAdapter(session, client.getRealm(), em, user);
    }
}
 
Example 3
Source File: KeycloakOIDCClientInstallation.java    From keycloak with Apache License 2.0 6 votes vote down vote up
static boolean showVerifyTokenAudience(ClientModel client) {
    // We want to verify-token-audience if service client has any client roles
    if (client.getRoles().size() > 0) {
        return true;
    }

    // Check if there is client scope with audience protocol mapper created for particular client. If yes, admin wants verifying token audience
    String clientId = client.getClientId();

    for (ClientScopeModel clientScope : client.getRealm().getClientScopes()) {
        for (ProtocolMapperModel protocolMapper : clientScope.getProtocolMappers()) {
            if (AudienceProtocolMapper.PROVIDER_ID.equals(protocolMapper.getProtocolMapper()) && (clientId.equals(protocolMapper.getConfig().get(AudienceProtocolMapper.INCLUDED_CLIENT_AUDIENCE)))) {
                return true;
            }
        }
    }

    return false;
}
 
Example 4
Source File: OIDCLoginProtocol.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean sendPushRevocationPolicyRequest(RealmModel realm, ClientModel resource, int notBefore, String managementUrl) {
    PushNotBeforeAction adminAction = new PushNotBeforeAction(TokenIdGenerator.generateId(), Time.currentTime() + 30, resource.getClientId(), notBefore);
    String token = session.tokens().encode(adminAction);
    logger.debugv("pushRevocation resource: {0} url: {1}", resource.getClientId(), managementUrl);
    URI target = UriBuilder.fromUri(managementUrl).path(AdapterConstants.K_PUSH_NOT_BEFORE).build();
    try {
        int status = session.getProvider(HttpClientProvider.class).postText(target.toString(), token);
        boolean success = status == 204 || status == 200;
        logger.debugf("pushRevocation success for %s: %s", managementUrl, success);
        return success;
    } catch (IOException e) {
        ServicesLogger.LOGGER.failedToSendRevocation(e);
        return false;
    }
}
 
Example 5
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 6
Source File: AuthenticationFlowResolver.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static AuthenticationFlowModel resolveBrowserFlow(AuthenticationSessionModel authSession) {
    AuthenticationFlowModel flow = null;
    ClientModel client = authSession.getClient();
    String clientFlow = client.getAuthenticationFlowBindingOverride(AuthenticationFlowBindings.BROWSER_BINDING);
    if (clientFlow != null) {
        flow = authSession.getRealm().getAuthenticationFlowById(clientFlow);
        if (flow == null) {
            throw new ModelException("Client " + client.getClientId() + " has browser flow override, but this flow does not exist");
        }
        return flow;
    }
    return authSession.getRealm().getBrowserFlow();
}
 
Example 7
Source File: AuthenticationFlowResolver.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static AuthenticationFlowModel resolveDirectGrantFlow(AuthenticationSessionModel authSession) {
    AuthenticationFlowModel flow = null;
    ClientModel client = authSession.getClient();
    String clientFlow = client.getAuthenticationFlowBindingOverride(AuthenticationFlowBindings.DIRECT_GRANT_BINDING);
    if (clientFlow != null) {
        flow = authSession.getRealm().getAuthenticationFlowById(clientFlow);
        if (flow == null) {
            throw new ModelException("Client " + client.getClientId() + " has direct grant flow override, but this flow does not exist");
        }
        return flow;
    }
    return authSession.getRealm().getDirectGrantFlow();
}
 
Example 8
Source File: ClientRemovedEvent.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static ClientRemovedEvent create(ClientModel client) {
    ClientRemovedEvent event = new ClientRemovedEvent();

    event.realmId = client.getRealm().getId();
    event.clientUuid = client.getId();
    event.clientId = client.getClientId();
    event.clientRoles = new HashMap<>();
    for (RoleModel clientRole : client.getRoles()) {
        event.clientRoles.put(clientRole.getId(), clientRole.getName());
    }

    return event;
}
 
Example 9
Source File: ApplicationsBean.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void processRoles(Set<RoleModel> inputRoles, List<RoleModel> realmRoles, MultivaluedHashMap<String, ClientRoleEntry> clientRoles) {
    for (RoleModel role : inputRoles) {
        if (role.getContainer() instanceof RealmModel) {
            realmRoles.add(role);
        } else {
            ClientModel currentClient = (ClientModel) role.getContainer();
            ClientRoleEntry clientRole = new ClientRoleEntry(currentClient.getClientId(), currentClient.getName(),
                    role.getName(), role.getDescription());
            clientRoles.add(currentClient.getClientId(), clientRole);
        }
    }
}
 
Example 10
Source File: Helper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static String getRolePolicyName(RoleModel role) {
    String roleName = "";
    if (role.getContainer() instanceof ClientModel) {
        ClientModel client = (ClientModel) role.getContainer();
        roleName = client.getClientId() + "." + role.getName();
    } else {
        roleName = role.getName();
    }
    roleName = "role.policy." + roleName;
    return roleName;
}
 
Example 11
Source File: ResourceAdminManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected boolean sendLogoutRequest(RealmModel realm, ClientModel resource, List<String> adapterSessionIds, List<String> userSessions, int notBefore, String managementUrl) {
    LogoutAction adminAction = new LogoutAction(TokenIdGenerator.generateId(), Time.currentTime() + 30, resource.getClientId(), adapterSessionIds, notBefore, userSessions);
    String token = session.tokens().encode(adminAction);
    if (logger.isDebugEnabled()) logger.debugv("logout resource {0} url: {1} sessionIds: " + adapterSessionIds, resource.getClientId(), managementUrl);
    URI target = UriBuilder.fromUri(managementUrl).path(AdapterConstants.K_LOGOUT).build();
    try {
        int status = session.getProvider(HttpClientProvider.class).postText(target.toString(), token);
        boolean success = status == 204 || status == 200;
        logger.debugf("logout success for %s: %s", managementUrl, success);
        return success;
    } catch (IOException e) {
        ServicesLogger.LOGGER.logoutFailed(e, resource.getClientId());
        return false;
    }
}
 
Example 12
Source File: ResourceAdminManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected boolean sendTestNodeAvailabilityRequest(RealmModel realm, ClientModel client, String managementUrl) {
     TestAvailabilityAction adminAction = new TestAvailabilityAction(TokenIdGenerator.generateId(), Time.currentTime() + 30, client.getClientId());
     String token = session.tokens().encode(adminAction);
     logger.debugv("testNodes availability resource: {0} url: {1}", client.getClientId(), managementUrl);
     URI target = UriBuilder.fromUri(managementUrl).path(AdapterConstants.K_TEST_AVAILABLE).build();
     try {
         int status = session.getProvider(HttpClientProvider.class).postText(target.toString(), token);
         boolean success = status == 204 || status == 200;
         logger.debugf("testAvailability success for %s: %s", managementUrl, success);
         return success;
     } catch (IOException e) {
         ServicesLogger.LOGGER.availabilityTestFailed(managementUrl);
         return false;
     }
}
 
Example 13
Source File: UserCacheSession.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public UserModel findServiceAccount(ClientModel client) {
    String username = ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + client.getClientId();
    logger.tracev("getServiceAccount: {0}", username);
    username = username.toLowerCase();
    RealmModel realm = client.getRealm();
    if (realmInvalidations.contains(realm.getId())) {
        logger.tracev("realmInvalidations");
        return getDelegate().getServiceAccount(client);
    }
    String cacheKey = getUserByUsernameCacheKey(realm.getId(), username);
    if (invalidations.contains(cacheKey)) {
        logger.tracev("invalidations");
        return getDelegate().getServiceAccount(client);
    }
    UserListQuery query = cache.get(cacheKey, UserListQuery.class);

    String userId = null;
    if (query == null) {
        logger.tracev("query null");
        Long loaded = cache.getCurrentRevision(cacheKey);
        UserModel model = getDelegate().getServiceAccount(client);
        if (model == null) {
            logger.tracev("model from delegate null");
            return null;
        }
        userId = model.getId();
        if (invalidations.contains(userId)) return model;
        if (managedUsers.containsKey(userId)) {
            logger.tracev("return managed user");
            return managedUsers.get(userId);
        }

        UserModel adapter = getUserAdapter(realm, userId, loaded, model);
        if (adapter instanceof UserAdapter) { // this was cached, so we can cache query too
            query = new UserListQuery(loaded, cacheKey, realm, model.getId());
            cache.addRevisioned(query, startupRevision);
        }
        managedUsers.put(userId, adapter);
        return adapter;
    } else {
        userId = query.getUsers().iterator().next();
        if (invalidations.contains(userId)) {
            logger.tracev("invalidated cache return delegate");
            return getDelegate().getUserByUsername(username, realm);

        }
        logger.trace("return getUserById");
        return getUserById(userId, realm);
    }
}
 
Example 14
Source File: ExportUtils.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Full export of role including composite roles
 * @param role
 * @return RoleRepresentation with all stuff filled (including composite roles)
 */
public static RoleRepresentation exportRole(RoleModel role) {
    RoleRepresentation roleRep = ModelToRepresentation.toRepresentation(role);

    Set<RoleModel> composites = role.getComposites();
    if (composites != null && composites.size() > 0) {
        Set<String> compositeRealmRoles = null;
        Map<String, List<String>> compositeClientRoles = null;

        for (RoleModel composite : composites) {
            RoleContainerModel crContainer = composite.getContainer();
            if (crContainer instanceof RealmModel) {

                if (compositeRealmRoles == null) {
                    compositeRealmRoles = new HashSet<>();
                }
                compositeRealmRoles.add(composite.getName());
            } else {
                if (compositeClientRoles == null) {
                    compositeClientRoles = new HashMap<>();
                }

                ClientModel app = (ClientModel)crContainer;
                String appName = app.getClientId();
                List<String> currentAppComposites = compositeClientRoles.get(appName);
                if (currentAppComposites == null) {
                    currentAppComposites = new ArrayList<>();
                    compositeClientRoles.put(appName, currentAppComposites);
                }
                currentAppComposites.add(composite.getName());
            }
        }

        RoleRepresentation.Composites compRep = new RoleRepresentation.Composites();
        if (compositeRealmRoles != null) {
            compRep.setRealm(compositeRealmRoles);
        }
        if (compositeClientRoles != null) {
            compRep.setClient(compositeClientRoles);
        }

        roleRep.setComposites(compRep);
    }

    return roleRep;
}
 
Example 15
Source File: ExportUtils.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Full export of user data stored in federated storage (including role mappings and credentials)
 *
 * @param id
 * @return fully exported user representation
 */
public static UserRepresentation exportFederatedUser(KeycloakSession session, RealmModel realm, String id, ExportOptions options) {
    UserRepresentation userRep = new UserRepresentation();
    userRep.setId(id);
    MultivaluedHashMap<String, String> attributes = session.userFederatedStorage().getAttributes(realm, id);
    if (attributes.size() > 0) {
        Map<String, List<String>> attrs = new HashMap<>();
        attrs.putAll(attributes);
        userRep.setAttributes(attrs);
    }

    Set<String> requiredActions = session.userFederatedStorage().getRequiredActions(realm, id);
    if (requiredActions.size() > 0) {
        List<String> actions = new LinkedList<>();
        actions.addAll(requiredActions);
        userRep.setRequiredActions(actions);
    }


    // Social links
    Set<FederatedIdentityModel> socialLinks = session.userFederatedStorage().getFederatedIdentities(id, realm);
    List<FederatedIdentityRepresentation> socialLinkReps = new ArrayList<>();
    for (FederatedIdentityModel socialLink : socialLinks) {
        FederatedIdentityRepresentation socialLinkRep = exportSocialLink(socialLink);
        socialLinkReps.add(socialLinkRep);
    }
    if (socialLinkReps.size() > 0) {
        userRep.setFederatedIdentities(socialLinkReps);
    }

    // Role mappings
    if (options.isGroupsAndRolesIncluded()) {
        Set<RoleModel> roles = session.userFederatedStorage().getRoleMappings(realm, id);
        List<String> realmRoleNames = new ArrayList<>();
        Map<String, List<String>> clientRoleNames = new HashMap<>();
        for (RoleModel role : roles) {
            if (role.getContainer() instanceof RealmModel) {
                realmRoleNames.add(role.getName());
            } else {
                ClientModel client = (ClientModel) role.getContainer();
                String clientId = client.getClientId();
                List<String> currentClientRoles = clientRoleNames.get(clientId);
                if (currentClientRoles == null) {
                    currentClientRoles = new ArrayList<>();
                    clientRoleNames.put(clientId, currentClientRoles);
                }

                currentClientRoles.add(role.getName());
            }
        }

        if (realmRoleNames.size() > 0) {
            userRep.setRealmRoles(realmRoleNames);
        }
        if (clientRoleNames.size() > 0) {
            userRep.setClientRoles(clientRoleNames);
        }
    }

    // Credentials
    List<CredentialModel> creds = session.userFederatedStorage().getStoredCredentials(realm, id);
    List<CredentialRepresentation> credReps = new ArrayList<>();
    for (CredentialModel cred : creds) {
        CredentialRepresentation credRep = exportCredential(cred);
        credReps.add(credRep);
    }
    userRep.setCredentials(credReps);

    // Grants
    List<UserConsentModel> consents = session.users().getConsents(realm, id);
    LinkedList<UserConsentRepresentation> consentReps = new LinkedList<>();
    for (UserConsentModel consent : consents) {
        UserConsentRepresentation consentRep = ModelToRepresentation.toRepresentation(consent);
        consentReps.add(consentRep);
    }
    if (consentReps.size() > 0) {
        userRep.setClientConsents(consentReps);
    }

    // Not Before
    int notBefore = session.userFederatedStorage().getNotBeforeOfUser(realm, userRep.getId());
    userRep.setNotBefore(notBefore);

    if (options.isGroupsAndRolesIncluded()) {
        List<String> groups = new LinkedList<>();
        for (GroupModel group : session.userFederatedStorage().getGroups(realm, id)) {
            groups.add(ModelToRepresentation.buildGroupPath(group));
        }
        userRep.setGroups(groups);
    }
    return userRep;
}