org.keycloak.models.utils.KeycloakModelUtils Java Examples

The following examples show how to use org.keycloak.models.utils.KeycloakModelUtils. 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: JPAPermissionTicketStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public PermissionTicket create(String resourceId, String scopeId, String requester, ResourceServer resourceServer) {
    PermissionTicketEntity entity = new PermissionTicketEntity();

    entity.setId(KeycloakModelUtils.generateId());
    entity.setResource(ResourceAdapter.toEntity(entityManager, provider.getStoreFactory().getResourceStore().findById(resourceId, resourceServer.getId())));
    entity.setRequester(requester);
    entity.setCreatedTimestamp(System.currentTimeMillis());

    if (scopeId != null) {
        entity.setScope(ScopeAdapter.toEntity(entityManager, provider.getStoreFactory().getScopeStore().findById(scopeId, resourceServer.getId())));
    }

    entity.setOwner(entity.getResource().getOwner());
    entity.setResourceServer(ResourceServerAdapter.toEntity(entityManager, resourceServer));

    this.entityManager.persist(entity);
    this.entityManager.flush();
    PermissionTicket model = new PermissionTicketAdapter(entity, entityManager, provider.getStoreFactory());
    return model;
}
 
Example #2
Source File: ConditionalRoleAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean matchCondition(AuthenticationFlowContext context) {
    UserModel user = context.getUser();
    RealmModel realm = context.getRealm();
    AuthenticatorConfigModel authConfig = context.getAuthenticatorConfig();
    if (user != null && authConfig!=null && authConfig.getConfig()!=null) {
        String requiredRole = authConfig.getConfig().get(ConditionalRoleAuthenticatorFactory.CONDITIONAL_USER_ROLE);
        RoleModel role = KeycloakModelUtils.getRoleFromString(realm, requiredRole);
        if (role == null) {
            logger.errorv("Invalid role name submitted: {0}", requiredRole);
            return false;
        }
        return user.hasRole(role);
    }
    return false;
}
 
Example #3
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 #4
Source File: AdminEventAuthDetailsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
    RealmBuilder realm = RealmBuilder.create().name("test").testEventListener();
    client1Uuid = KeycloakModelUtils.generateId();
    realm.client(ClientBuilder.create().id(client1Uuid).clientId("client1").publicClient().directAccessGrants());

    admin1Id =  KeycloakModelUtils.generateId();
    realm.user(UserBuilder.create().id(admin1Id).username("admin1").password("password").role(Constants.REALM_MANAGEMENT_CLIENT_ID, AdminRoles.REALM_ADMIN));

    admin2Id =  KeycloakModelUtils.generateId();
    realm.user(UserBuilder.create().id(admin2Id).username("admin2").password("password").role(Constants.REALM_MANAGEMENT_CLIENT_ID, AdminRoles.REALM_ADMIN));

    appUserId =  KeycloakModelUtils.generateId();
    realm.user(UserBuilder.create().id(appUserId).username("app-user").password("password"));

    testRealms.add(realm.build());
}
 
Example #5
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 #6
Source File: JpaUserFederatedStorageProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public CredentialModel createCredential(RealmModel realm, String userId, CredentialModel cred) {
    createIndex(realm, userId);
    FederatedUserCredentialEntity entity = new FederatedUserCredentialEntity();
    String id = cred.getId() == null ? KeycloakModelUtils.generateId() : cred.getId();
    entity.setId(id);
    entity.setCreatedDate(cred.getCreatedDate());
    entity.setType(cred.getType());
    entity.setCredentialData(cred.getCredentialData());
    entity.setSecretData(cred.getSecretData());
    entity.setUserLabel(cred.getUserLabel());

    entity.setUserId(userId);
    entity.setRealmId(realm.getId());
    entity.setStorageProviderId(new StorageId(userId).getProviderId());

    //add in linkedlist to last position
    List<FederatedUserCredentialEntity> credentials = getStoredCredentialEntities(userId);
    int priority = credentials.isEmpty() ? JpaUserCredentialStore.PRIORITY_DIFFERENCE : credentials.get(credentials.size() - 1).getPriority() + JpaUserCredentialStore.PRIORITY_DIFFERENCE;
    entity.setPriority(priority);

    em.persist(entity);
    return toModel(entity);
}
 
Example #7
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static List<ClientScopeModel> getClientScopesToApproveOnConsentScreen(RealmModel realm, UserConsentModel grantedConsent,
                                                                              AuthenticationSessionModel authSession) {
    // Client Scopes to be displayed on consent screen
    List<ClientScopeModel> clientScopesToDisplay = new LinkedList<>();

    for (String clientScopeId : authSession.getClientScopes()) {
        ClientScopeModel clientScope = KeycloakModelUtils.findClientScopeById(realm, authSession.getClient(), clientScopeId);

        if (clientScope == null || !clientScope.isDisplayOnConsentScreen()) {
            continue;
        }

        // Check if consent already granted by user
        if (grantedConsent == null || !grantedConsent.isClientScopeGranted(clientScope)) {
            clientScopesToDisplay.add(clientScope);
        }
    }

    return clientScopesToDisplay;
}
 
Example #8
Source File: JPAScopeStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public Scope create(String id, final String name, final ResourceServer resourceServer) {
    ScopeEntity entity = new ScopeEntity();

    if (id == null) {
        entity.setId(KeycloakModelUtils.generateId());
    } else {
        entity.setId(id);
    }

    entity.setName(name);
    entity.setResourceServer(ResourceServerAdapter.toEntity(entityManager, resourceServer));

    this.entityManager.persist(entity);
    this.entityManager.flush();

    return new ScopeAdapter(entity, entityManager, provider.getStoreFactory());
}
 
Example #9
Source File: ClientAdapter.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public ProtocolMapperModel addProtocolMapper(ProtocolMapperModel model) {
    if (getProtocolMapperByName(model.getProtocol(), model.getName()) != null) {
        throw new ModelDuplicateException("Protocol mapper name must be unique per protocol");
    }
    String id = model.getId() != null ? model.getId() : KeycloakModelUtils.generateId();
    ProtocolMapperEntity entity = new ProtocolMapperEntity();
    entity.setId(id);
    entity.setName(model.getName());
    entity.setProtocol(model.getProtocol());
    entity.setProtocolMapper(model.getProtocolMapper());
    entity.setClient(this.entity);
    entity.setConfig(model.getConfig());

    em.persist(entity);
    this.entity.getProtocolMappers().add(entity);
    return entityToModel(entity);
}
 
Example #10
Source File: RealmAdapter.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void setConfig(ComponentModel model, ComponentEntity c) {
    c.getComponentConfigs().clear();
    for (String key : model.getConfig().keySet()) {
        List<String> vals = model.getConfig().get(key);
        if (vals == null) {
            continue;
        }
        for (String val : vals) {
            ComponentConfigEntity config = new ComponentConfigEntity();
            config.setId(KeycloakModelUtils.generateId());
            config.setName(key);
            config.setValue(val);
            config.setComponent(c);
            c.getComponentConfigs().add(config);
        }
    }
}
 
Example #11
Source File: ClientScopeAdapter.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public ProtocolMapperModel addProtocolMapper(ProtocolMapperModel model) {
    if (getProtocolMapperByName(model.getProtocol(), model.getName()) != null) {
        throw new ModelDuplicateException("Protocol mapper name must be unique per protocol");
    }
    String id = model.getId() != null ? model.getId() : KeycloakModelUtils.generateId();
    ProtocolMapperEntity entity = new ProtocolMapperEntity();
    entity.setId(id);
    entity.setName(model.getName());
    entity.setProtocol(model.getProtocol());
    entity.setProtocolMapper(model.getProtocolMapper());
    entity.setClientScope(this.entity);
    entity.setConfig(model.getConfig());

    em.persist(entity);
    this.entity.getProtocolMappers().add(entity);
    return entityToModel(entity);
}
 
Example #12
Source File: SingleFileExportProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void exportModel(KeycloakSessionFactory factory) throws IOException {
    logger.infof("Exporting model into file %s", this.file.getAbsolutePath());
    KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {

        @Override
        protected void runExportImportTask(KeycloakSession session) throws IOException {
            List<RealmModel> realms = session.realms().getRealms();
            List<RealmRepresentation> reps = new ArrayList<>();
            for (RealmModel realm : realms) {
                reps.add(ExportUtils.exportRealm(session, realm, true, true));
            }

            writeToFile(reps);
        }

    });

}
 
Example #13
Source File: UserStorageSyncManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void updateLastSyncInterval(final KeycloakSessionFactory sessionFactory, UserStorageProviderModel provider, final String realmId) {
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            RealmModel persistentRealm = session.realms().getRealm(realmId);
            List<UserStorageProviderModel> persistentFedProviders = persistentRealm.getUserStorageProviders();
            for (UserStorageProviderModel persistentFedProvider : persistentFedProviders) {
                if (provider.getId().equals(persistentFedProvider.getId())) {
                    // Update persistent provider in DB
                    int lastSync = Time.currentTime();
                    persistentFedProvider.setLastSync(lastSync);
                    persistentRealm.updateComponent(persistentFedProvider);

                    // Update "cached" reference
                    provider.setLastSync(lastSync);
                }
            }
        }

    });
}
 
Example #14
Source File: ImpersonationConstants.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void setupMasterRealmRole(RealmProvider model, RealmModel realm) {
    RealmModel adminRealm;
    RoleModel adminRole;

    if (realm.getName().equals(Config.getAdminRealm())) {
        adminRealm = realm;
        adminRole = realm.getRole(AdminRoles.ADMIN);
    } else {
        adminRealm = model.getRealm(Config.getAdminRealm());
        adminRole = adminRealm.getRole(AdminRoles.ADMIN);
    }
    ClientModel realmAdminApp = adminRealm.getClientByClientId(KeycloakModelUtils.getMasterRealmAdminApplicationClientId(realm.getName()));
    if (realmAdminApp.getRole(IMPERSONATION_ROLE) != null) return;
    RoleModel impersonationRole = realmAdminApp.addRole(IMPERSONATION_ROLE);
    impersonationRole.setDescription("${role_" + IMPERSONATION_ROLE + "}");
    adminRole.addCompositeRole(impersonationRole);
}
 
Example #15
Source File: RealmAdapter.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public IdentityProviderMapperModel addIdentityProviderMapper(IdentityProviderMapperModel model) {
    if (getIdentityProviderMapperByName(model.getIdentityProviderAlias(), model.getName()) != null) {
        throw new RuntimeException("identity provider mapper name must be unique per identity provider");
    }
    String id = KeycloakModelUtils.generateId();
    IdentityProviderMapperEntity entity = new IdentityProviderMapperEntity();
    entity.setId(id);
    entity.setName(model.getName());
    entity.setIdentityProviderAlias(model.getIdentityProviderAlias());
    entity.setIdentityProviderMapper(model.getIdentityProviderMapper());
    entity.setRealm(this.realm);
    entity.setConfig(model.getConfig());

    em.persist(entity);
    this.realm.getIdentityProviderMappers().add(entity);
    return entityToModel(entity);
}
 
Example #16
Source File: ClientAttributeCertificateResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a new certificate with new key pair
 *
 * @return
 */
@POST
@NoCache
@Path("generate")
@Produces(MediaType.APPLICATION_JSON)
public CertificateRepresentation generate() {
    auth.clients().requireConfigure(client);

    CertificateRepresentation info = KeycloakModelUtils.generateKeyPairCertificate(client.getClientId());

    CertificateInfoHelper.updateClientModelCertificateInfo(client, info, attributePrefix);

    adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).representation(info).success();

    return info;
}
 
Example #17
Source File: LDAPTestUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void addOrUpdateGroupMapper(RealmModel realm, ComponentModel providerModel, LDAPGroupMapperMode mode, String descriptionAttrName, String... otherConfigOptions) {
    ComponentModel mapperModel = getSubcomponentByName(realm, providerModel, "groupsMapper");
    if (mapperModel != null) {
        mapperModel.getConfig().putSingle(GroupMapperConfig.MODE, mode.toString());
        updateGroupMapperConfigOptions(mapperModel, otherConfigOptions);
        realm.updateComponent(mapperModel);
    } else {
        String baseDn = providerModel.getConfig().getFirst(LDAPConstants.BASE_DN);
        mapperModel = KeycloakModelUtils.createComponentModel("groupsMapper", providerModel.getId(), GroupLDAPStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(),
                GroupMapperConfig.GROUPS_DN, "ou=Groups," + baseDn,
                GroupMapperConfig.MAPPED_GROUP_ATTRIBUTES, descriptionAttrName,
                GroupMapperConfig.PRESERVE_GROUP_INHERITANCE, "true",
                GroupMapperConfig.MODE, mode.toString(),
                GroupMapperConfig.LDAP_GROUPS_PATH, "/");
        updateGroupMapperConfigOptions(mapperModel, otherConfigOptions);
        realm.addComponentModel(mapperModel);
    }
}
 
Example #18
Source File: UserStorageSyncManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Check federationProviderModel of all realms and possibly start periodic sync for them
 *
 * @param sessionFactory
 * @param timer
 */
public void bootstrapPeriodic(final KeycloakSessionFactory sessionFactory, final TimerProvider timer) {
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            List<RealmModel> realms = session.realms().getRealmsWithProviderType(UserStorageProvider.class);
            for (final RealmModel realm : realms) {
                List<UserStorageProviderModel> providers = realm.getUserStorageProviders();
                for (final UserStorageProviderModel provider : providers) {
                    UserStorageProviderFactory factory = (UserStorageProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(UserStorageProvider.class, provider.getProviderId());
                    if (factory instanceof ImportSynchronization && provider.isImportEnabled()) {
                        refreshPeriodicSyncForProvider(sessionFactory, timer, provider, realm.getId());
                    }
                }
            }

            ClusterProvider clusterProvider = session.getProvider(ClusterProvider.class);
            clusterProvider.registerListener(USER_STORAGE_TASK_KEY, new UserStorageClusterListener(sessionFactory));
        }
    });
}
 
Example #19
Source File: MigrateTo1_8_0.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void migrateRealm(RealmModel realm) {
    List<UserStorageProviderModel> federationProviders = realm.getUserStorageProviders();
    for (UserStorageProviderModel fedProvider : federationProviders) {

        if (fedProvider.getProviderId().equals(LDAPConstants.LDAP_PROVIDER)) {

            if (isActiveDirectory(fedProvider)) {
                // Create mapper for MSAD account controls
                if (getMapperByName(realm, fedProvider, "MSAD account controls") == null) {
                    ComponentModel mapperModel = KeycloakModelUtils.createComponentModel("MSAD account controls", fedProvider.getId(), LDAPConstants.MSAD_USER_ACCOUNT_CONTROL_MAPPER, "org.keycloak.storage.ldap.mappers.LDAPStorageMapper");
                    realm.addComponentModel(mapperModel);
                }
            }
        }
    }
}
 
Example #20
Source File: MigrationUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void migrateOldOfflineToken(KeycloakSession session, RealmModel realm, ClientModel client, UserModel user) throws OAuthErrorException {
    ClientScopeModel offlineScope = KeycloakModelUtils.getClientScopeByName(realm, OAuth2Constants.OFFLINE_ACCESS);
    if (offlineScope == null) {
        throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Offline Access scope not found");
    }

    if (client.isConsentRequired()) {
        // Automatically add consents for client and for offline_access. We know that both were defacto approved by user already and offlineSession is still valid
        UserConsentModel consent = session.users().getConsentByClient(realm, user.getId(), client.getId());
        if (consent != null) {
            if (client.isDisplayOnConsentScreen()) {
                consent.addGrantedClientScope(client);
            }
            if (offlineScope.isDisplayOnConsentScreen()) {
                consent.addGrantedClientScope(offlineScope);
            }
            session.users().updateConsent(realm, user.getId(), consent);
        }
    }
}
 
Example #21
Source File: EntitlementAPITest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@NotNull
private JSPolicyRepresentation createOnlyOwnerPolicy() {
    JSPolicyRepresentation onlyOwnerPolicy = new JSPolicyRepresentation();

    onlyOwnerPolicy.setName(KeycloakModelUtils.generateId());
    onlyOwnerPolicy.setCode("var context = $evaluation.getContext();\n" +
            "var identity = context.getIdentity();\n" +
            "var permission = $evaluation.getPermission();\n" +
            "var resource = permission.getResource();\n" +
            "\n" +
            "if (resource) {\n" +
            "    if (resource.owner == identity.id) {\n" +
            "        $evaluation.grant();\n" +
            "    }\n" +
            "}");

    return onlyOwnerPolicy;
}
 
Example #22
Source File: MultipleStepsExportProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void exportModel(KeycloakSessionFactory factory) throws IOException {
    final RealmsHolder holder = new RealmsHolder();

    KeycloakModelUtils.runJobInTransaction(factory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            List<RealmModel> realms = session.realms().getRealms();
            holder.realms = realms;
        }

    });

    for (RealmModel realm : holder.realms) {
        exportRealmImpl(factory, realm.getName());
    }
}
 
Example #23
Source File: SingleFileImportProvider.java    From keycloak-export with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void importModel(KeycloakSessionFactory factory, Strategy strategy) throws IOException {
    logger.infof("Full importing from file %s", this.file.getAbsolutePath());

    BetterRealmRepresentation masterRealm = getMasterRealm();
    KeycloakModelUtils.runJobInTransaction(factory, session -> {
        // Import master realm first, if exists
        if (masterRealm != null) {
            importRealm(session, masterRealm, strategy);
        }
        realmReps.stream().filter(r -> r != masterRealm).forEach(r -> importRealm(session, r, strategy));

        if (masterRealm != null) {
            // If master was imported, we may need to re-create realm management clients
            for (RealmModel realm : session.realms().getRealms()) {
                if (realm.getMasterAdminClient() == null) {
                    logger.infof("Re-created management client in master realm for realm '%s'", realm.getName());
                    new RealmManager(session).setupMasterAdminManagement(realm);
                }
            }
        }
    });
}
 
Example #24
Source File: AbstractCommand.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void runCommand() {
    try {
        KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

            @Override
            public void run(KeycloakSession session) {
                doRunCommand(session);
            }

        });
    } catch (HandledException handled) {
        // Fine to ignore. Was handled already
    } catch (RuntimeException e) {
        log.error("Error occured during command. ", e);
    }
}
 
Example #25
Source File: LDAPMultipleAttributesTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void afterImportTestRealm() {
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();

        LDAPTestUtils.addZipCodeLDAPMapper(appRealm, ctx.getLdapModel());
        LDAPTestUtils.addUserAttributeMapper(appRealm, ctx.getLdapModel(), "streetMapper", "street", LDAPConstants.STREET);

        // Remove current users and add default users
        LDAPStorageProvider ldapFedProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel());
        LDAPTestUtils.removeAllLDAPUsers(ldapFedProvider, appRealm);

        LDAPObject james = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "jbrown", "James", "Brown", "[email protected]", null, "88441");
        LDAPTestUtils.updateLDAPPassword(ldapFedProvider, james, "Password1");

        // User for testing duplicating surname and postalCode
        LDAPObject bruce = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "bwilson", "Bruce", "Wilson", "[email protected]", "Elm 5", "88441", "77332");
        bruce.setAttribute("sn", new LinkedHashSet<>(Arrays.asList("Wilson", "Schneider")));
        ldapFedProvider.getLdapIdentityStore().update(bruce);
        LDAPTestUtils.updateLDAPPassword(ldapFedProvider, bruce, "Password1");

        // Create ldap-portal client
        ClientModel ldapClient = KeycloakModelUtils.createClient(appRealm, "ldap-portal");
        ldapClient.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        ldapClient.addRedirectUri("/ldap-portal");
        ldapClient.addRedirectUri("/ldap-portal/*");
        ldapClient.setManagementUrl("/ldap-portal");
        ldapClient.addProtocolMapper(UserAttributeMapper.createClaimMapper("postalCode", "postal_code", "postal_code", "String", true, true, true));
        ldapClient.addProtocolMapper(UserAttributeMapper.createClaimMapper("street", "street", "street", "String", true, true, false));
        ldapClient.addScopeMapping(appRealm.getRole("user"));
        ldapClient.setSecret("password");
    });
}
 
Example #26
Source File: UserAdapter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void persistAttributeValue(String name, String value) {
    UserAttributeEntity attr = new UserAttributeEntity();
    attr.setId(KeycloakModelUtils.generateId());
    attr.setName(name);
    attr.setValue(value);
    attr.setUser(user);
    em.persist(attr);
    user.getAttributes().add(attr);
}
 
Example #27
Source File: ClientAttributeCertificateResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a new keypair and certificate, and get the private key file
 *
 * Generates a keypair and certificate and serves the private key in a specified keystore format.
 * Only generated public certificate is saved in Keycloak DB - the private key is not.
 *
 * @param config Keystore configuration as JSON
 * @return
 */
@POST
@NoCache
@Path("/generate-and-download")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes(MediaType.APPLICATION_JSON)
public byte[] generateAndGetKeystore(final KeyStoreConfig config) {
    auth.clients().requireConfigure(client);

    if (config.getFormat() != null && !config.getFormat().equals("JKS") && !config.getFormat().equals("PKCS12")) {
        throw new NotAcceptableException("Only support jks or pkcs12 format.");
    }
    if (config.getKeyPassword() == null) {
        throw new ErrorResponseException("password-missing", "Need to specify a key password for jks generation and download", Response.Status.BAD_REQUEST);
    }
    if (config.getStorePassword() == null) {
        throw new ErrorResponseException("password-missing", "Need to specify a store password for jks generation and download", Response.Status.BAD_REQUEST);
    }

    CertificateRepresentation info = KeycloakModelUtils.generateKeyPairCertificate(client.getClientId());
    byte[] rtn = getKeystore(config, info.getPrivateKey(), info.getCertificate());

    info.setPrivateKey(null);

    CertificateInfoHelper.updateClientModelCertificateInfo(client, info, attributePrefix);

    adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).representation(info).success();
    return rtn;
}
 
Example #28
Source File: ScopeMappedClientResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Get the roles associated with a client's scope
 *
 * Returns roles for the client.
 *
 * @return
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public List<RoleRepresentation> getClientScopeMappings() {
    viewPermission.require();

    Set<RoleModel> mappings = KeycloakModelUtils.getClientScopeMappings(scopedClient, scopeContainer); //scopedClient.getClientScopeMappings(client);
    List<RoleRepresentation> mapRep = new ArrayList<RoleRepresentation>();
    for (RoleModel roleModel : mappings) {
        mapRep.add(ModelToRepresentation.toBriefRepresentation(roleModel));
    }
    return mapRep;
}
 
Example #29
Source File: QuarkusJpaConnectionProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void lazyInit() {
    Instance<EntityManagerFactory> instance = CDI.current().select(EntityManagerFactory.class);

    if (!instance.isResolvable()) {
        throw new RuntimeException("Failed to resolve " + EntityManagerFactory.class + " from Quarkus runtime");
    }

    emf = instance.get();

    try (Connection connection = getConnection()) {
        if (jtaEnabled) {
            KeycloakModelUtils.suspendJtaTransaction(factory, () -> {
                KeycloakSession session = factory.create();
                try {
                    migration(getSchema(), connection, session);
                } finally {
                    session.close();
                }
            });
        } else {
            KeycloakModelUtils.runJobInTransaction(factory, session -> {
                migration(getSchema(), connection, session);
            });
        }
        prepareOperationalInfo(connection);
    } catch (SQLException cause) {
        throw new RuntimeException("Failed to migrate model", cause);
    }
}
 
Example #30
Source File: ExampleServiceImpl.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public CompanyRepresentation addCompany(CompanyRepresentation company) {
    Company entity = new Company();
    String id = company.getId()==null ?  KeycloakModelUtils.generateId() : company.getId();
    entity.setId(id);
    entity.setName(company.getName());
    entity.setRealmId(getRealm().getId());
    getEntityManager().persist(entity);

    company.setId(id);
    return company;
}