org.keycloak.models.ClientModel Java Examples

The following examples show how to use org.keycloak.models.ClientModel. 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: ConsentRequiredClientRegistrationPolicy.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeUpdate(ClientRegistrationContext context, ClientModel clientModel) throws ClientRegistrationPolicyException {
    if (context.getClient().isConsentRequired() == null) {
        return;
    }
    if (clientModel == null) {
        return;
    }

    boolean isEnabled = clientModel.isConsentRequired();
    boolean newEnabled = context.getClient().isConsentRequired();

    if (isEnabled && !newEnabled) {
        throw new ClientRegistrationPolicyException("Not permitted to update consentRequired to false");
    }
}
 
Example #2
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void createFederatedRoleMappings(UserFederatedStorageProvider federatedStorage, UserRepresentation userRep, 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());
            }
            federatedStorage.grantRole(realm, userRep.getId(), 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());
            }
            createFederatedClientRoleMappings(federatedStorage, realm, client, userRep, entry.getValue());
        }
    }
}
 
Example #3
Source File: RolePolicyProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void onExport(Policy policy, PolicyRepresentation representation, AuthorizationProvider authorizationProvider) {
    Map<String, String> config = new HashMap<>();
    Set<RolePolicyRepresentation.RoleDefinition> roles = toRepresentation(policy, authorizationProvider).getRoles();

    for (RolePolicyRepresentation.RoleDefinition roleDefinition : roles) {
        RoleModel role = authorizationProvider.getRealm().getRoleById(roleDefinition.getId());

        if (role.isClientRole()) {
            roleDefinition.setId(ClientModel.class.cast(role.getContainer()).getClientId() + "/" + role.getName());
        } else {
            roleDefinition.setId(role.getName());
        }
    }

    try {
        config.put("roles", JsonSerialization.writeValueAsString(roles));
    } catch (IOException cause) {
        throw new RuntimeException("Failed to export role policy [" + policy.getName() + "]", cause);
    }

    representation.setConfig(config);
}
 
Example #4
Source File: DeviceActivityTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void ipTest() {
    final String ip = "146.58.69.12";

    String sessionId = "abcdefg";
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName(TEST);
        ClientModel client = session.clientLocalStorage().getClientByClientId(TEST_CLIENT_ID, realm);
        UserModel user = session.users().getUserByUsername("test", realm); // cannot use testUser.getUsername() because it throws NotSerializableException for no apparent reason (or maybe I'm just stupid :D)

        UserSessionModel userSession = session.sessions().createUserSession(sessionId, realm, user, "test", ip, "form", false, null, null);
        session.sessions().createClientSession(realm, client, userSession);
    });

    deviceActivityPage.clickRefreshPage();

    assertEquals(ip, deviceActivityPage.getSession(sessionId).getIp());
}
 
Example #5
Source File: ClientManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Should not be called from an import.  This really expects that the client is created from the admin console.
 *
 * @param session
 * @param realm
 * @param rep
 * @param addDefaultRoles
 * @return
 */
public static ClientModel createClient(KeycloakSession session, RealmModel realm, ClientRepresentation rep, boolean addDefaultRoles) {
    ClientModel client = RepresentationToModel.createClient(session, realm, rep, addDefaultRoles);

    if (rep.getProtocol() != null) {
        LoginProtocolFactory providerFactory = (LoginProtocolFactory) session.getKeycloakSessionFactory().getProviderFactory(LoginProtocol.class, rep.getProtocol());
        providerFactory.setupClientDefaults(rep, client);
    }


    // remove default mappers if there is a template
    if (rep.getProtocolMappers() == null && rep.getClientTemplate() != null) {
        Set<ProtocolMapperModel> mappers = client.getProtocolMappers();
        for (ProtocolMapperModel mapper : mappers) client.removeProtocolMapper(mapper);
    }
    return client;

}
 
Example #6
Source File: ClientManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public InstallationAdapterConfig toInstallationRepresentation(RealmModel realmModel, ClientModel clientModel, URI baseUri) {
    InstallationAdapterConfig rep = new InstallationAdapterConfig();
    rep.setAuthServerUrl(baseUri.toString());
    rep.setRealm(realmModel.getName());
    rep.setSslRequired(realmModel.getSslRequired().name().toLowerCase());

    if (clientModel.isPublicClient() && !clientModel.isBearerOnly()) rep.setPublicClient(true);
    if (clientModel.isBearerOnly()) rep.setBearerOnly(true);
    if (clientModel.getRoles().size() > 0) rep.setUseResourceRoleMappings(true);

    rep.setResource(clientModel.getClientId());

    if (showClientCredentialsAdapterConfig(clientModel)) {
        Map<String, Object> adapterConfig = getClientCredentialsAdapterConfig(clientModel);
        rep.setCredentials(adapterConfig);
    }

    return rep;
}
 
Example #7
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 #8
Source File: DummyClientAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticateClient(ClientAuthenticationFlowContext context) {
    ClientIdAndSecretAuthenticator authenticator = new ClientIdAndSecretAuthenticator();
    authenticator.authenticateClient(context);
    if (context.getStatus().equals(FlowStatus.SUCCESS)) {
        return;
    }

    String clientId = context.getUriInfo().getQueryParameters().getFirst("client_id");

    if (clientId == null) {
        clientId = context.getSession().getAttribute("client_id", String.class);
    }

    ClientModel client = context.getRealm().getClientByClientId(clientId);
    if (client == null) {
        context.failure(AuthenticationFlowError.CLIENT_NOT_FOUND, null);
        return;
    }

    context.getEvent().client(client);
    context.setClient(client);
    context.success();
}
 
Example #9
Source File: ClientModelTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private ClientModel setUpClient(RealmModel realm) {
    ClientModel client = realm.addClient("application");
    client.setName("Application");
    client.setDescription("Description");
    client.setBaseUrl("http://base");
    client.setManagementUrl("http://management");
    client.setClientId("app-name");
    client.setProtocol("openid-connect");
    client.addRole("role-1");
    client.addRole("role-2");
    client.addRole("role-3");
    client.addDefaultRole("role-1");
    client.addDefaultRole("role-2");
    client.addRedirectUri("redirect-1");
    client.addRedirectUri("redirect-2");
    client.addWebOrigin("origin-1");
    client.addWebOrigin("origin-2");
    client.registerNode("node1", 10);
    client.registerNode("10.20.30.40", 50);
    client.addProtocolMapper(AddressMapper.createAddressMapper());
    client.updateClient();
    return client;
}
 
Example #10
Source File: RealmManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void checkRealmAdminManagementRoles(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);
    RoleModel adminRole = realmAdminClient.getRole(AdminRoles.REALM_ADMIN);

    // if realm-admin role isn't in the realm model, create it
    if (adminRole == null) {
        adminRole = realmAdminClient.addRole(AdminRoles.REALM_ADMIN);
        adminRole.setDescription("${role_" + AdminRoles.REALM_ADMIN + "}");
    }

    for (String r : AdminRoles.ALL_REALM_ROLES) {
        RoleModel found = realmAdminClient.getRole(r);
        if (found == null) {
            addAndSetAdminRole(r, realmAdminClient, adminRole);
        }
    }
    addQueryCompositeRoles(realmAdminClient);
}
 
Example #11
Source File: RoleLDAPStorageMapper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public Set<RoleModel> getClientRoleMappings(ClientModel client) {
    if (roleContainer.equals(client)) {
        Set<RoleModel> ldapRoleMappings = getLDAPRoleMappingsConverted();

        if (config.getMode() == LDAPGroupMapperMode.LDAP_ONLY) {
            // Use just role mappings from LDAP
            return ldapRoleMappings;
        } else {
            // Merge mappings from both DB and LDAP
            Set<RoleModel> modelRoleMappings = super.getClientRoleMappings(client);
            ldapRoleMappings.addAll(modelRoleMappings);
            return ldapRoleMappings;
        }
    } else {
        return super.getClientRoleMappings(client);
    }
}
 
Example #12
Source File: MigrateTo1_5_0.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void migrateRealm(RealmModel realm) {
    DefaultAuthenticationFlows.migrateFlows(realm); // add reset credentials flo
    realm.setOTPPolicy(OTPPolicy.DEFAULT_POLICY);
    realm.setBrowserFlow(realm.getFlowByAlias(DefaultAuthenticationFlows.BROWSER_FLOW));
    realm.setRegistrationFlow(realm.getFlowByAlias(DefaultAuthenticationFlows.REGISTRATION_FLOW));
    realm.setDirectGrantFlow(realm.getFlowByAlias(DefaultAuthenticationFlows.DIRECT_GRANT_FLOW));

    AuthenticationFlowModel resetFlow = realm.getFlowByAlias(DefaultAuthenticationFlows.RESET_CREDENTIALS_FLOW);
    if (resetFlow == null) {
        DefaultAuthenticationFlows.resetCredentialsFlow(realm);
    } else {
        realm.setResetCredentialsFlow(resetFlow);
    }

    AuthenticationFlowModel clientAuthFlow = realm.getFlowByAlias(DefaultAuthenticationFlows.CLIENT_AUTHENTICATION_FLOW);
    if (clientAuthFlow == null) {
        DefaultAuthenticationFlows.clientAuthFlow(realm);
    } else {
        realm.setClientAuthenticationFlow(clientAuthFlow);
    }

    for (ClientModel client : realm.getClients()) {
        client.setClientAuthenticatorType(KeycloakModelUtils.getDefaultClientAuthenticatorType());
    }
}
 
Example #13
Source File: MigrateTo6_0_0.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void migrateRealm(KeycloakSession session, RealmModel realm, boolean jsn) {
    MigrationProvider migrationProvider = session.getProvider(MigrationProvider.class);

    // create 'microprofile-jwt' optional client scope in the realm.
    ClientScopeModel mpJWTScope = migrationProvider.addOIDCMicroprofileJWTClientScope(realm);

    LOG.debugf("Added '%s' optional client scope", mpJWTScope.getName());

    // assign 'microprofile-jwt' optional client scope to all the OIDC clients.
    for (ClientModel client : realm.getClients()) {
        if ((client.getProtocol() == null || "openid-connect".equals(client.getProtocol())) && (!client.isBearerOnly())) {
            client.addClientScope(mpJWTScope, false);
        }
    }

    LOG.debugf("Client scope '%s' assigned to all the clients", mpJWTScope.getName());
}
 
Example #14
Source File: RoleCommands.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private RoleContainerModel getRoleContainer(KeycloakSession session, String roleContainer) {
    String[] parts = roleContainer.split("/");
    String realmName = parts[0];

    RealmModel realm = session.realms().getRealmByName(realmName);
    if (realm == null) {
        log.errorf("Unknown realm: %s", realmName);
        throw new HandledException();
    }

    if (parts.length == 1) {
        return realm;
    } else {
        String clientId = parts[1];
        ClientModel client = session.realms().getClientByClientId(clientId, realm);
        if (client == null) {
            log.errorf("Unknown client: %s", clientId);
            throw new HandledException();
        }

        return client;
    }
}
 
Example #15
Source File: AbstractOAuth2IdentityProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected Response exchangeStoredToken(UriInfo uriInfo, EventBuilder event, ClientModel authorizedClient, UserSessionModel tokenUserSession, UserModel tokenSubject) {
    FederatedIdentityModel model = session.users().getFederatedIdentity(tokenSubject, getConfig().getAlias(), authorizedClient.getRealm());
    if (model == null || model.getToken() == null) {
        event.detail(Details.REASON, "requested_issuer is not linked");
        event.error(Errors.INVALID_TOKEN);
        return exchangeNotLinked(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
    }
    String accessToken = extractTokenFromResponse(model.getToken(), getAccessTokenResponseParameter());
    if (accessToken == null) {
        model.setToken(null);
        session.users().updateFederatedIdentity(authorizedClient.getRealm(), tokenSubject, model);
        event.detail(Details.REASON, "requested_issuer token expired");
        event.error(Errors.INVALID_TOKEN);
        return exchangeTokenExpired(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
    }
    AccessTokenResponse tokenResponse = new AccessTokenResponse();
    tokenResponse.setToken(accessToken);
    tokenResponse.setIdToken(null);
    tokenResponse.setRefreshToken(null);
    tokenResponse.setRefreshExpiresIn(0);
    tokenResponse.getOtherClaims().clear();
    tokenResponse.getOtherClaims().put(OAuth2Constants.ISSUED_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE);
    tokenResponse.getOtherClaims().put(ACCOUNT_LINK_URL, getLinkingUrl(uriInfo, authorizedClient, tokenUserSession));
    event.success();
    return Response.ok(tokenResponse).type(MediaType.APPLICATION_JSON_TYPE).build();
}
 
Example #16
Source File: DefaultClientSessionContext.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private boolean isClientScopePermittedForUser(ClientScopeModel clientScope) {
    if (clientScope instanceof ClientModel) {
        return true;
    }

    Set<RoleModel> clientScopeRoles = clientScope.getScopeMappings();

    // Client scope is automatically permitted if it doesn't have any role scope mappings
    if (clientScopeRoles.isEmpty()) {
        return true;
    }

    // Expand (resolve composite roles)
    clientScopeRoles = RoleUtils.expandCompositeRoles(clientScopeRoles);

    // Check if expanded roles of clientScope has any intersection with expanded roles of user. If not, it is not permitted
    clientScopeRoles.retainAll(getUserRoles());
    return !clientScopeRoles.isEmpty();
}
 
Example #17
Source File: ResourceAdminManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected GlobalRequestResult pushRevocationPolicy(RealmModel realm, ClientModel resource, int notBefore) {
    List<String> mgmtUrls = getAllManagementUrls(resource);
    if (mgmtUrls.isEmpty()) {
        logger.debugf("No management URL or no registered cluster nodes for the client %s", resource.getClientId());
        return new GlobalRequestResult();
    }

    if (logger.isDebugEnabled()) logger.debug("Sending push revocation to URLS: " + mgmtUrls);

    // Propagate this to all hosts
    GlobalRequestResult result = new GlobalRequestResult();
    for (String mgmtUrl : mgmtUrls) {
        if (sendPushRevocationPolicyRequest(realm, resource, notBefore, mgmtUrl)) {
            result.addSuccessRequest(mgmtUrl);
        } else {
            result.addFailedRequest(mgmtUrl);
        }
    }
    return result;
}
 
Example #18
Source File: TestCacheUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static void cacheRoles(KeycloakSession session, RealmModel realm, RoleContainerModel roleContainer) {
    for (RoleModel role : roleContainer.getRoles()) {
        realm.getRoleById(role.getId());
        roleContainer.getRole(role.getName());
        if (roleContainer instanceof RealmModel) {
            session.realms().getRealmRole(realm, role.getName());
        } else {
            session.realms().getClientRole(realm, (ClientModel) roleContainer, role.getName());
        }
    }
}
 
Example #19
Source File: UserCacheSession.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public UserModel getServiceAccount(ClientModel client) {
    // Just an attempt to find the user from cache by default serviceAccount username
    UserModel user = findServiceAccount(client);
    if (user != null && user.getServiceAccountClientLink() != null && user.getServiceAccountClientLink().equals(client.getId())) {
        return user;
    }

    return getDelegate().getServiceAccount(client);
}
 
Example #20
Source File: JpaRealmProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean removeClient(String id, RealmModel realm) {
    final ClientModel client = getClientById(id, realm);
    if (client == null) return false;

    session.users().preRemove(realm, client);

    for (RoleModel role : client.getRoles()) {
        // No need to go through cache. Roles were already invalidated
        removeRole(realm, role);
    }

    ClientEntity clientEntity = em.find(ClientEntity.class, id, LockModeType.PESSIMISTIC_WRITE);

    session.getKeycloakSessionFactory().publish(new RealmModel.ClientRemovedEvent() {
        @Override
        public ClientModel getClient() {
            return client;
        }

        @Override
        public KeycloakSession getKeycloakSession() {
            return session;
        }
    });

    int countRemoved = em.createNamedQuery("deleteClientScopeClientMappingByClient")
            .setParameter("client", clientEntity)
            .executeUpdate();
    em.remove(clientEntity);  // i have no idea why, but this needs to come before deleteScopeMapping

    try {
        em.flush();
    } catch (RuntimeException e) {
        logger.errorv("Unable to delete client entity: {0} from realm {1}", client.getClientId(), realm.getName());
        throw e;
    }

    return true;
}
 
Example #21
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 #22
Source File: PolicyEvaluationTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void testCheckUserAttributes(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("authz-test");
    UserModel jdoe = session.users().getUserByUsername("jdoe", realm);

    jdoe.setAttribute("a1", Arrays.asList("1", "2"));
    jdoe.setSingleAttribute("a2", "3");

    session.getContext().setRealm(realm);
    AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
    ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm());
    StoreFactory storeFactory = authorization.getStoreFactory();
    ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId());
    JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();

    policyRepresentation.setName("testCheckUserAttributes");
    StringBuilder builder = new StringBuilder();

    builder.append("var realm = $evaluation.getRealm();");
    builder.append("var attributes = realm.getUserAttributes('jdoe');");
    builder.append("if (attributes.size() == 6 && attributes.containsKey('a1') && attributes.containsKey('a2') && attributes.get('a1').size() == 2 && attributes.get('a2').get(0).equals('3')) { $evaluation.grant(); }");

    policyRepresentation.setCode(builder.toString());

    Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
    PolicyProvider provider = authorization.getProvider(policy.getType());

    DefaultEvaluation evaluation = createEvaluation(session, authorization, resourceServer, policy);

    provider.evaluate(evaluation);

    Assert.assertEquals(Effect.PERMIT, evaluation.getEffect());
}
 
Example #23
Source File: JpaRealmProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public ClientModel getClientByClientId(String clientId, RealmModel realm) {
    TypedQuery<String> query = em.createNamedQuery("findClientIdByClientId", String.class);
    query.setParameter("clientId", clientId);
    query.setParameter("realm", realm.getId());
    List<String> results = query.getResultList();
    if (results.isEmpty()) return null;
    String id = results.get(0);
    return session.realms().getClientById(id, realm);
}
 
Example #24
Source File: DefaultClientSessionContext.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public String getScopeString() {
    StringBuilder builder = new StringBuilder();

    // Add both default and optional scopes to scope parameter. Don't add client itself
    boolean first = true;
    for (ClientScopeModel clientScope : getClientScopes()) {
        if (clientScope instanceof ClientModel) {
            continue;
        }

        if (!clientScope.isIncludeInTokenScope()) {
            continue;
        }

        if (first) {
            first = false;
        } else {
            builder.append(" ");
        }
        builder.append(clientScope.getName());
    }

    String scopeParam = builder.toString();

    // See if "openid" scope is requested
    String scopeSent = clientSession.getNote(OAuth2Constants.SCOPE);
    if (TokenUtil.isOIDCRequest(scopeSent)) {
        scopeParam = TokenUtil.attachOIDCScope(scopeParam);
    }

    return scopeParam;
}
 
Example #25
Source File: IllegalAdminUpgradeTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void setupUsers(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName(TEST);
    RealmModel master = session.realms().getRealmByName("master");
    ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
    ClientModel realmMasterAdminClient = realm.getMasterAdminClient();
    RoleModel realmManageUsers = realmAdminClient.getRole(AdminRoles.MANAGE_USERS);
    RoleModel masterManageUsers = realmMasterAdminClient.getRole(AdminRoles.MANAGE_USERS);
    RoleModel masterMasterManageUSers = master.getMasterAdminClient().getRole(AdminRoles.MANAGE_USERS);

    UserModel realmUser = session.users().addUser(realm, "userAdmin");
    realmUser.grantRole(realmManageUsers);
    realmUser.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, realmUser, UserCredentialModel.password("password"));

    UserModel masterUser = session.users().addUser(master, "userAdmin");
    masterUser.grantRole(masterManageUsers);
    masterUser.setEnabled(true);
    session.userCredentialManager().updateCredential(master, masterUser, UserCredentialModel.password("password"));

    UserModel masterAdmin = session.users().addUser(master, "masterAdmin");
    masterAdmin.grantRole(masterMasterManageUSers);
    masterAdmin.setEnabled(true);
    session.userCredentialManager().updateCredential(master, masterAdmin, UserCredentialModel.password("password"));

    UserModel user = session.users().addUser(master, "user");
    user.grantRole(masterManageUsers);
    user.setEnabled(true);
    session.userCredentialManager().updateCredential(master, user, UserCredentialModel.password("password"));

    user = session.users().addUser(realm, "user");
    user.grantRole(realmManageUsers);
    user.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password("password"));
}
 
Example #26
Source File: AdminConsole.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Adapter configuration for the admin console for this realm
 *
 * @return
 */
@Path("config")
@GET
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public ClientManager.InstallationAdapterConfig config() {
    ClientModel consoleApp = realm.getClientByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID);
    if (consoleApp == null) {
        throw new NotFoundException("Could not find admin console client");
    }
    return new ClientManager(new RealmManager(session)).toInstallationRepresentation(realm, consoleApp, session.getContext().getUri().getBaseUri());    }
 
Example #27
Source File: DockerVariableOverrideInstallationProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Response generateInstallation(final KeycloakSession session, final RealmModel realm, final ClientModel client, final URI serverBaseUri) {
    final StringBuilder builder = new StringBuilder()
            .append("-e REGISTRY_AUTH_TOKEN_REALM=").append(serverBaseUri).append("/realms/").append(realm.getName()).append("/protocol/").append(DockerAuthV2Protocol.LOGIN_PROTOCOL).append("/auth \\\n")
            .append("-e REGISTRY_AUTH_TOKEN_SERVICE=").append(client.getClientId()).append(" \\\n")
            .append("-e REGISTRY_AUTH_TOKEN_ISSUER=").append(serverBaseUri).append("/realms/").append(realm.getName()).append(" \\\n");
    return Response.ok(builder.toString(), MediaType.TEXT_PLAIN_TYPE).build();
}
 
Example #28
Source File: ClientAdapter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof ClientModel)) return false;

    ClientModel that = (ClientModel) o;
    return that.getId().equals(getId());
}
 
Example #29
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 #30
Source File: DefaultClientRegistrationProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@GET
@Path("{clientId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getDefault(@PathParam("clientId") String clientId) {
    ClientModel client = session.getContext().getRealm().getClientByClientId(clientId);
    ClientRepresentation clientRepresentation = get(client);
    return Response.ok(clientRepresentation).build();
}