org.keycloak.component.ComponentModel Java Examples
The following examples show how to use
org.keycloak.component.ComponentModel.
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: LDAPLegacyImportTest.java From keycloak with Apache License 2.0 | 6 votes |
@Override protected void afterImportTestRealm() { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); ComponentModel ldapModel = appRealm.getComponents(appRealm.getId(), UserStorageProvider.class.getName()).get(0); LDAPTestUtils.addLocalUser(session, appRealm, "marykeycloak", "[email protected]", "password-app"); // Delete all LDAP users and add some new for testing LDAPStorageProvider ldapFedProvider = LDAPTestUtils.getLdapProvider(session, ldapModel); LDAPTestUtils.removeAllLDAPUsers(ldapFedProvider, appRealm); LDAPObject john = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "johnkeycloak", "John", "Doe", "[email protected]", null, "1234"); LDAPTestUtils.updateLDAPPassword(ldapFedProvider, john, "Password1"); LDAPObject existing = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "existing", "Existing", "Foo", "[email protected]", null, "5678"); appRealm.getClientByClientId("test-app").setDirectAccessGrantsEnabled(true); }); }
Example #2
Source File: KeycloakModelUtils.java From keycloak with Apache License 2.0 | 6 votes |
public static ComponentModel createComponentModel(String name, String parentId, String providerId, String providerType, String... config) { ComponentModel mapperModel = new ComponentModel(); mapperModel.setParentId(parentId); mapperModel.setName(name); mapperModel.setProviderId(providerId); mapperModel.setProviderType(providerType); String key = null; for (String configEntry : config) { if (key == null) { key = configEntry; } else { mapperModel.getConfig().add(key, configEntry); key = null; } } if (key != null) { throw new IllegalStateException("Invalid count of arguments for config. Maybe mistake?"); } return mapperModel; }
Example #3
Source File: LDAPGroupMapper2WaySyncTest.java From keycloak with Apache License 2.0 | 6 votes |
private static void testDropNonExisting(KeycloakSession session, LDAPTestContext ctx, ComponentModel mapperModel) { RealmModel realm = ctx.getRealm(); // Put some group directly to LDAP LDAPTestUtils.createLDAPGroup(session, realm, ctx.getLdapModel(), "group3"); // Sync and assert our group is still in LDAP SynchronizationResult syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromKeycloakToFederationProvider(realm); LDAPTestAsserts.assertSyncEquals(syncResult, 0, 4, 0, 0); Assert.assertNotNull(LDAPTestUtils.getGroupMapper(mapperModel, ctx.getLdapProvider(), realm).loadLDAPGroupByName("group3")); // Change config to drop non-existing groups LDAPTestUtils.updateGroupMapperConfigOptions(mapperModel, GroupMapperConfig.DROP_NON_EXISTING_GROUPS_DURING_SYNC, "true"); realm.updateComponent(mapperModel); // Sync and assert group removed from LDAP syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromKeycloakToFederationProvider(realm); LDAPTestAsserts.assertSyncEquals(syncResult, 0, 4, 1, 0); Assert.assertNull(LDAPTestUtils.getGroupMapper(mapperModel, ctx.getLdapProvider(), realm).loadLDAPGroupByName("group3")); }
Example #4
Source File: LDAPStorageProviderFactory.java From keycloak with Apache License 2.0 | 6 votes |
/** * !! This function must be called from try-with-resources block, otherwise Vault secrets may be leaked !! * @param sessionFactory * @param realmId * @param model * @return */ private LDAPQuery createQuery(KeycloakSessionFactory sessionFactory, final String realmId, final ComponentModel model) { class QueryHolder { LDAPQuery query; } final QueryHolder queryHolder = new QueryHolder(); KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() { @Override public void run(KeycloakSession session) { session.getContext().setRealm(session.realms().getRealm(realmId)); LDAPStorageProvider ldapFedProvider = (LDAPStorageProvider)session.getProvider(UserStorageProvider.class, model); RealmModel realm = session.realms().getRealm(realmId); queryHolder.query = LDAPUtils.createQueryForUserSearch(ldapFedProvider, realm); } }); return queryHolder.query; }
Example #5
Source File: DefaultKeycloakSession.java From keycloak with Apache License 2.0 | 6 votes |
@Override public <T extends Provider> T getProvider(Class<T> clazz, ComponentModel componentModel) { String modelId = componentModel.getId(); Object found = getAttribute(modelId); if (found != null) { return clazz.cast(found); } ProviderFactory<T> providerFactory = factory.getProviderFactory(clazz, componentModel.getProviderId()); if (providerFactory == null) { return null; } @SuppressWarnings("unchecked") ComponentFactory<T, T> componentFactory = (ComponentFactory<T, T>) providerFactory; T provider = componentFactory.create(this, componentModel); enlistForClose(provider); setAttribute(modelId, provider); return provider; }
Example #6
Source File: RoleLDAPStorageMapperFactory.java From keycloak with Apache License 2.0 | 6 votes |
@Override public void validateConfiguration(KeycloakSession session, RealmModel realm, ComponentModel config) throws ComponentValidationException { checkMandatoryConfigAttribute(RoleMapperConfig.ROLES_DN, "LDAP Roles DN", config); checkMandatoryConfigAttribute(RoleMapperConfig.MODE, "Mode", config); String realmMappings = config.getConfig().getFirst(RoleMapperConfig.USE_REALM_ROLES_MAPPING); boolean useRealmMappings = Boolean.parseBoolean(realmMappings); if (!useRealmMappings) { String clientId = config.getConfig().getFirst(RoleMapperConfig.CLIENT_ID); if (clientId == null || clientId.trim().isEmpty()) { throw new ComponentValidationException("ldapErrorMissingClientId"); } } LDAPUtils.validateCustomLdapFilter(config.getConfig().getFirst(RoleMapperConfig.ROLES_LDAP_FILTER)); }
Example #7
Source File: GeneratedEcdsaKeyProviderFactory.java From keycloak with Apache License 2.0 | 6 votes |
@Override public boolean createFallbackKeys(KeycloakSession session, KeyUse keyUse, String algorithm) { if (keyUse.equals(KeyUse.SIG) && (algorithm.equals(Algorithm.ES256) || algorithm.equals(Algorithm.ES384) || algorithm.equals(Algorithm.ES512))) { RealmModel realm = session.getContext().getRealm(); ComponentModel generated = new ComponentModel(); generated.setName("fallback-" + algorithm); generated.setParentId(realm.getId()); generated.setProviderId(ID); generated.setProviderType(KeyProvider.class.getName()); MultivaluedHashMap<String, String> config = new MultivaluedHashMap<>(); config.putSingle(Attributes.PRIORITY_KEY, "-100"); config.putSingle(ECDSA_ELLIPTIC_CURVE_KEY, convertAlgorithmToECDomainParmNistRep(algorithm)); generated.setConfig(config); realm.addComponentModel(generated); return true; } else { return false; } }
Example #8
Source File: RepresentationToModel.java From keycloak with Apache License 2.0 | 6 votes |
public static ComponentModel convertFedProviderToComponent(String realmId, UserFederationProviderRepresentation fedModel) { UserStorageProviderModel model = new UserStorageProviderModel(); model.setId(fedModel.getId()); model.setName(fedModel.getDisplayName()); model.setParentId(realmId); model.setProviderId(fedModel.getProviderName()); model.setProviderType(UserStorageProvider.class.getName()); model.setFullSyncPeriod(fedModel.getFullSyncPeriod()); model.setPriority(fedModel.getPriority()); model.setChangedSyncPeriod(fedModel.getChangedSyncPeriod()); model.setLastSync(fedModel.getLastSync()); if (fedModel.getConfig() != null) { for (Map.Entry<String, String> entry : fedModel.getConfig().entrySet()) { model.getConfig().putSingle(entry.getKey(), entry.getValue()); } } return model; }
Example #9
Source File: MigrateTo1_8_0.java From keycloak with Apache License 2.0 | 6 votes |
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 #10
Source File: UserStorageProviderResource.java From keycloak with Apache License 2.0 | 6 votes |
/** * Unlink imported users from a storage provider * * * @param id * @return */ @POST @Path("{id}/unlink-users") @NoCache public void unlinkUsers(@PathParam("id") String id) { auth.users().requireManage(); ComponentModel model = realm.getComponent(id); if (model == null) { throw new NotFoundException("Could not find component"); } if (!model.getProviderType().equals(UserStorageProvider.class.getName())) { throw new NotFoundException("found, but not a UserStorageProvider"); } session.users().unlinkUsers(realm, id); }
Example #11
Source File: RealmAdapter.java From keycloak with Apache License 2.0 | 6 votes |
@Override public void updateComponent(ComponentModel component) { ComponentUtil.getComponentFactory(session, component).validateConfiguration(session, this, component); ComponentEntity c = getComponentEntity(component.getId()); if (c == null) return; ComponentModel old = entityToModel(c); c.setName(component.getName()); c.setProviderId(component.getProviderId()); c.setProviderType(component.getProviderType()); c.setParentId(component.getParentId()); c.setSubType(component.getSubType()); setConfig(component, c); ComponentUtil.notifyUpdated(session, this, old, component); }
Example #12
Source File: GeneratedEcdsaKeyProvider.java From keycloak with Apache License 2.0 | 6 votes |
@Override protected KeyWrapper loadKey(RealmModel realm, ComponentModel model) { String privateEcdsaKeyBase64Encoded = model.getConfig().getFirst(GeneratedEcdsaKeyProviderFactory.ECDSA_PRIVATE_KEY_KEY); String publicEcdsaKeyBase64Encoded = model.getConfig().getFirst(GeneratedEcdsaKeyProviderFactory.ECDSA_PUBLIC_KEY_KEY); String ecInNistRep = model.getConfig().getFirst(GeneratedEcdsaKeyProviderFactory.ECDSA_ELLIPTIC_CURVE_KEY); try { PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.decode(privateEcdsaKeyBase64Encoded)); KeyFactory kf = KeyFactory.getInstance("EC"); PrivateKey decodedPrivateKey = kf.generatePrivate(privateKeySpec); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.decode(publicEcdsaKeyBase64Encoded)); PublicKey decodedPublicKey = kf.generatePublic(publicKeySpec); KeyPair keyPair = new KeyPair(decodedPublicKey, decodedPrivateKey); return createKeyWrapper(keyPair, ecInNistRep); } catch (Exception e) { logger.warnf("Exception at decodeEcdsaPublicKey. %s", e.toString()); return null; } }
Example #13
Source File: LdapManyObjectsInitializerCommand.java From keycloak with Apache License 2.0 | 5 votes |
private ComponentModel getMapperModel(RealmModel realm, ComponentModel ldapModel, String mapperName) { List<ComponentModel> ldapMappers = realm.getComponents(ldapModel.getId(), LDAPStorageMapper.class.getName()); Optional<ComponentModel> optional = ldapMappers.stream().filter((ComponentModel mapper) -> { return mapper.getName().equals(mapperName); }).findFirst(); if (!optional.isPresent()) { log.errorf("Not present LDAP mapper called '%s'", mapperName); throw new HandledException(); } return optional.get(); }
Example #14
Source File: RealmAdapter.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void removeComponent(ComponentModel component) { getDelegateForUpdate(); executeEvictions(component); updated.removeComponent(component); }
Example #15
Source File: RepresentationToModel.java From keycloak with Apache License 2.0 | 5 votes |
public static ComponentModel toModel(KeycloakSession session, ComponentRepresentation rep) { ComponentModel model = new ComponentModel(); model.setId(rep.getId()); model.setParentId(rep.getParentId()); model.setProviderType(rep.getProviderType()); model.setProviderId(rep.getProviderId()); model.setConfig(new MultivaluedHashMap<>()); model.setName(rep.getName()); model.setSubType(rep.getSubType()); if (rep.getConfig() != null) { Set<String> keys = new HashSet<>(rep.getConfig().keySet()); for (String k : keys) { List<String> values = rep.getConfig().get(k); if (values != null) { ListIterator<String> itr = values.listIterator(); while (itr.hasNext()) { String v = itr.next(); if (v == null || v.trim().isEmpty()) { itr.remove(); } } if (!values.isEmpty()) { model.getConfig().put(k, values); } } } } return model; }
Example #16
Source File: AbstractEcdsaKeyProviderFactory.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void validateConfiguration(KeycloakSession session, RealmModel realm, ComponentModel model) throws ComponentValidationException { ConfigurationValidationHelper.check(model) .checkLong(Attributes.PRIORITY_PROPERTY, false) .checkBoolean(Attributes.ENABLED_PROPERTY, false) .checkBoolean(Attributes.ACTIVE_PROPERTY, false); }
Example #17
Source File: UserStorageManager.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void onUpdate(KeycloakSession session, RealmModel realm, ComponentModel oldModel, ComponentModel newModel) { ComponentFactory factory = ComponentUtil.getComponentFactory(session, newModel); if (!(factory instanceof UserStorageProviderFactory)) return; UserStorageProviderModel old = new UserStorageProviderModel(oldModel); UserStorageProviderModel newP= new UserStorageProviderModel(newModel); if (old.getChangedSyncPeriod() != newP.getChangedSyncPeriod() || old.getFullSyncPeriod() != newP.getFullSyncPeriod() || old.isImportEnabled() != newP.isImportEnabled()) { new UserStorageSyncManager().notifyToRefreshPeriodicSync(session, realm, new UserStorageProviderModel(newModel), false); } }
Example #18
Source File: LDAPTestContext.java From keycloak with Apache License 2.0 | 5 votes |
public static LDAPTestContext init(KeycloakSession session) { RealmModel testRealm = session.realms().getRealm(AbstractLDAPTest.TEST_REALM_NAME); ComponentModel ldapCompModel = LDAPTestUtils.getLdapProviderModel(session, testRealm); UserStorageProviderModel ldapModel = new UserStorageProviderModel(ldapCompModel); LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ldapModel); return new LDAPTestContext(testRealm, ldapModel, ldapProvider); }
Example #19
Source File: LDAPStorageProvider.java From keycloak with Apache License 2.0 | 5 votes |
public LDAPStorageProvider(LDAPStorageProviderFactory factory, KeycloakSession session, ComponentModel model, LDAPIdentityStore ldapIdentityStore) { this.factory = factory; this.session = session; this.model = new UserStorageProviderModel(model); this.ldapIdentityStore = ldapIdentityStore; this.kerberosConfig = new LDAPProviderKerberosConfig(model); this.editMode = ldapIdentityStore.getConfig().getEditMode(); this.mapperManager = new LDAPStorageMapperManager(this); this.userManager = new LDAPStorageUserManager(this); supportedCredentialTypes.add(PasswordCredentialModel.TYPE); if (kerberosConfig.isAllowKerberosAuthentication()) { supportedCredentialTypes.add(UserCredentialModel.KERBEROS); } }
Example #20
Source File: DefaultClientRegistrationPolicies.java From keycloak with Apache License 2.0 | 5 votes |
public static void addDefaultPolicies(RealmModel realm) { String anonPolicyType = ClientRegistrationPolicyManager.getComponentTypeKey(RegistrationAuth.ANONYMOUS); String authPolicyType = ClientRegistrationPolicyManager.getComponentTypeKey(RegistrationAuth.AUTHENTICATED); List<ComponentModel> policies = realm.getComponents(realm.getId(), ClientRegistrationPolicy.class.getName()); // Probably an issue if admin removes all policies intentionally... if (policies == null ||policies.isEmpty()) { addAnonymousPolicies(realm, anonPolicyType); addAuthPolicies(realm, authPolicyType); } }
Example #21
Source File: LDAPBinaryAttributesTest.java From keycloak with Apache License 2.0 | 5 votes |
private static String addPhotoMapper(KeycloakTestingClient testingClient) { return testingClient.server().fetch(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); ComponentModel ldapComponentMapper = LDAPTestUtils.addUserAttributeMapper(appRealm, ctx.getLdapModel(), "jpeg-mapper", LDAPConstants.JPEG_PHOTO, LDAPConstants.JPEG_PHOTO); ldapComponentMapper.put(UserAttributeLDAPStorageMapper.IS_BINARY_ATTRIBUTE, true); ldapComponentMapper.put(UserAttributeLDAPStorageMapper.ALWAYS_READ_VALUE_FROM_LDAP, true); appRealm.updateComponent(ldapComponentMapper); return ldapComponentMapper.getId(); }, String.class); }
Example #22
Source File: SyncFederationTest.java From keycloak with Apache License 2.0 | 5 votes |
private static final UserStorageProviderModel findDummyProviderModel(RealmModel realm) { for (ComponentModel component : realm.getComponents()) { if ("test-sync-dummy".equals(component.getName())) { return new UserStorageProviderModel(component); } } return null; }
Example #23
Source File: LDAPStorageProviderFactory.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void preRemove(KeycloakSession session, RealmModel realm, ComponentModel model) { String allowKerberosCfg = model.getConfig().getFirst(KerberosConstants.ALLOW_KERBEROS_AUTHENTICATION); if (Boolean.valueOf(allowKerberosCfg)) { CredentialHelper.setOrReplaceAuthenticationRequirement(session, realm, CredentialRepresentation.KERBEROS, AuthenticationExecutionModel.Requirement.DISABLED, null); } }
Example #24
Source File: TestLDAPResource.java From keycloak with Apache License 2.0 | 5 votes |
/** * @param ldapCfg configuration of LDAP provider * @param importEnabled specify if LDAP provider will have import enabled * @return ID of newly created provider */ @POST @Path("/create-ldap-provider") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public String createLDAPProvider(Map<String,String> ldapCfg, @QueryParam("import") boolean importEnabled) { MultivaluedHashMap<String, String> ldapConfig = toComponentConfig(ldapCfg); ldapConfig.putSingle(LDAPConstants.SYNC_REGISTRATIONS, "true"); ldapConfig.putSingle(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.WRITABLE.toString()); UserStorageProviderModel model = new UserStorageProviderModel(); model.setLastSync(0); model.setChangedSyncPeriod(-1); model.setFullSyncPeriod(-1); model.setName("test-ldap"); model.setPriority(0); model.setProviderId(LDAPStorageProviderFactory.PROVIDER_NAME); model.setConfig(ldapConfig); model.setImportEnabled(importEnabled); model.setCachePolicy(UserStorageProviderModel.CachePolicy.MAX_LIFESPAN); model.setMaxLifespan(600000); // Lifetime is 10 minutes ComponentModel ldapModel = realm.addComponentModel(model); return ldapModel.getId(); }
Example #25
Source File: MSADUserAccountControlStorageMapperFactory.java From keycloak with Apache License 2.0 | 5 votes |
private static List<ProviderConfigProperty> getConfigProps(ComponentModel parent) { return ProviderConfigurationBuilder.create() .property().name(MSADUserAccountControlStorageMapper.LDAP_PASSWORD_POLICY_HINTS_ENABLED) .label("Password Policy Hints Enabled") .helpText("Applicable just for writable MSAD. If on, then updating password of MSAD user will use LDAP_SERVER_POLICY_HINTS_OID " + "extension, which means that advanced MSAD password policies like 'password history' or 'minimal password age' will be applied. This extension works just for MSAD 2008 R2 or newer.") .type(ProviderConfigProperty.BOOLEAN_TYPE) .defaultValue("false") .add() .build(); }
Example #26
Source File: UserCacheSession.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void preRemove(RealmModel realm, ComponentModel component) { if (!component.getProviderType().equals(UserStorageProvider.class.getName()) && !component.getProviderType().equals(ClientStorageProvider.class.getName())) return; addRealmInvalidation(realm.getId()); // easier to just invalidate whole realm getDelegate().preRemove(realm, component); }
Example #27
Source File: LDAPTestUtils.java From keycloak with Apache License 2.0 | 5 votes |
public static ComponentModel addUserAttributeMapper(RealmModel realm, ComponentModel providerModel, String mapperName, String userModelAttributeName, String ldapAttributeName) { ComponentModel mapperModel = KeycloakModelUtils.createComponentModel(mapperName, providerModel.getId(), UserAttributeLDAPStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(), UserAttributeLDAPStorageMapper.USER_MODEL_ATTRIBUTE, userModelAttributeName, UserAttributeLDAPStorageMapper.LDAP_ATTRIBUTE, ldapAttributeName, UserAttributeLDAPStorageMapper.READ_ONLY, "false", UserAttributeLDAPStorageMapper.ALWAYS_READ_VALUE_FROM_LDAP, "false", UserAttributeLDAPStorageMapper.IS_MANDATORY_IN_LDAP, "false"); return realm.addComponentModel(mapperModel); }
Example #28
Source File: LDAPTestUtils.java From keycloak with Apache License 2.0 | 5 votes |
public static ComponentModel getSubcomponentByName(RealmModel realm, ComponentModel providerModel, String name) { List<ComponentModel> components = realm.getComponents(providerModel.getId(), LDAPStorageMapper.class.getName()); for (ComponentModel component : components) { if (component.getName().equals(name)) { return component; } } return null; }
Example #29
Source File: LDAPTestUtils.java From keycloak with Apache License 2.0 | 5 votes |
public static void updateGroupMapperConfigOptions(ComponentModel mapperModel, String... configOptions) { for (int i=0 ; i<configOptions.length ; i+=2) { String cfgName = configOptions[i]; String cfgValue = configOptions[i+1]; mapperModel.getConfig().putSingle(cfgName, cfgValue); } }
Example #30
Source File: RealmAdapter.java From keycloak with Apache License 2.0 | 5 votes |
@Override public ComponentModel importComponentModel(ComponentModel model) { ComponentFactory componentFactory = null; try { componentFactory = ComponentUtil.getComponentFactory(session, model); if (componentFactory == null && System.getProperty(COMPONENT_PROVIDER_EXISTS_DISABLED) == null) { throw new IllegalArgumentException("Invalid component type"); } componentFactory.validateConfiguration(session, this, model); } catch (Exception e) { if (System.getProperty(COMPONENT_PROVIDER_EXISTS_DISABLED) == null) { throw e; } } ComponentEntity c = new ComponentEntity(); if (model.getId() == null) { c.setId(KeycloakModelUtils.generateId()); } else { c.setId(model.getId()); } c.setName(model.getName()); c.setParentId(model.getParentId()); if (model.getParentId() == null) { c.setParentId(this.getId()); model.setParentId(this.getId()); } c.setProviderType(model.getProviderType()); c.setProviderId(model.getProviderId()); c.setSubType(model.getSubType()); c.setRealm(realm); em.persist(c); realm.getComponents().add(c); setConfig(model, c); model.setId(c.getId()); return model; }