/** * Endpoint for executing reset credentials flow. If code is null, a client session is created * with the account service as the client. Successful reset sends you to the account page. Note, * account service must be enabled. * * @param code * @param execution * @return */ @Path(RESET_CREDENTIALS_PATH) @GET public Response resetCredentialsGET( @QueryParam("code") String code, @QueryParam("execution") String execution) { // we allow applications to link to reset credentials without going through OAuth or SAML // handshakes // if (code == null) { if (!realm.isResetPasswordAllowed()) { event.event(EventType.RESET_PASSWORD); event.error(Errors.NOT_ALLOWED); return ErrorPage.error(session, Messages.RESET_CREDENTIAL_NOT_ALLOWED); } // set up the account service as the endpoint to call. ClientModel client = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID); ClientSessionModel clientSession = session.sessions().createClientSession(realm, client); clientSession.setAction(ClientSessionModel.Action.AUTHENTICATE.name()); clientSession.setNote(ClientSessionCode.ACTION_KEY, KeycloakModelUtils.generateCodeSecret()); // clientSession.setNote(AuthenticationManager.END_AFTER_REQUIRED_ACTIONS, "true"); clientSession.setAuthMethod(OIDCLoginProtocol.LOGIN_PROTOCOL); String redirectUri = Urls.accountBase(uriInfo.getBaseUri()).path("/").build(realm.getName()).toString(); clientSession.setRedirectUri(redirectUri); clientSession.setAction(ClientSessionModel.Action.AUTHENTICATE.name()); clientSession.setNote(ClientSessionCode.ACTION_KEY, KeycloakModelUtils.generateCodeSecret()); clientSession.setNote(OIDCLoginProtocol.RESPONSE_TYPE_PARAM, OAuth2Constants.CODE); clientSession.setNote(OIDCLoginProtocol.REDIRECT_URI_PARAM, redirectUri); clientSession.setNote( OIDCLoginProtocol.ISSUER, Urls.realmIssuer(uriInfo.getBaseUri(), realm.getName())); return processResetCredentials(null, clientSession, null); } return resetCredentials(code, execution); }
@Override public void insertEntity(MongoIdentifiableEntity entity, MongoStoreInvocationContext context) { Class<? extends MongoEntity> clazz = entity.getClass(); // Find annotations for ID, for all the properties and for the name of the collection. EntityInfo entityInfo = getEntityInfo(clazz); // Create instance of BasicDBObject and add all declared properties to it (properties with null // value probably should be skipped) BasicDBObject dbObject = mapperRegistry.convertApplicationObjectToDBObject(entity, BasicDBObject.class); DBCollection dbCollection = database.getCollection(entityInfo.getDbCollectionName()); String currentId = entity.getId(); // Generate random ID if not set already if (currentId == null) { currentId = KeycloakModelUtils.generateId(); entity.setId(currentId); } // Adding "_id" dbObject.put("_id", currentId); try { dbCollection.insert(dbObject); } catch (MongoException e) { throw convertException(e); } // Treat object as created in this transaction (It is already submited to transaction) context.addCreatedEntity(entity); }
@Override public void updateCredential(UserCredentialModel cred) { CredentialEntity credentialEntity = getCredentialEntity(user, cred.getType()); if (credentialEntity == null) { credentialEntity = new CredentialEntity(); credentialEntity.setId(KeycloakModelUtils.generateId()); credentialEntity.setType(cred.getType()); credentialEntity.setDevice(cred.getDevice()); credentialEntity.setUser(user); em.persist(credentialEntity); user.getCredentials().add(credentialEntity); } if (cred.getType().equals(UserCredentialModel.PASSWORD)) { byte[] salt = getSalt(); int hashIterations = 1; PasswordPolicy policy = realm.getPasswordPolicy(); if (policy != null) { hashIterations = policy.getHashIterations(); if (hashIterations == -1) hashIterations = 1; } credentialEntity.setValue( new Pbkdf2PasswordEncoder(salt).encode(cred.getValue(), hashIterations)); credentialEntity.setSalt(salt); credentialEntity.setHashIterations(hashIterations); } else { credentialEntity.setValue(cred.getValue()); } credentialEntity.setDevice(cred.getDevice()); em.flush(); }
protected AccessToken initToken( RealmModel realm, ClientModel client, UserModel user, UserSessionModel session, ClientSessionModel clientSession) { AccessToken token = new AccessToken(); if (clientSession != null) token.clientSession(clientSession.getId()); token.id(KeycloakModelUtils.generateId()); token.subject(user.getId()); token.audience(client.getClientId()); token.issuedNow(); token.issuedFor(client.getClientId()); token.issuer(clientSession.getNote(OIDCLoginProtocol.ISSUER)); if (session != null) { token.setSessionState(session.getId()); } if (realm.getAccessTokenLifespan() > 0) { token.expiration(Time.currentTime() + realm.getAccessTokenLifespan()); } Set<String> allowedOrigins = client.getWebOrigins(); if (allowedOrigins != null) { token.setAllowedOrigins(allowedOrigins); } return token; }
public static void addOrUpdateGroupMapper( RealmModel realm, UserFederationProviderModel providerModel, LDAPGroupMapperMode mode, String descriptionAttrName, String... otherConfigOptions) { UserFederationMapperModel mapperModel = realm.getUserFederationMapperByName(providerModel.getId(), "groupsMapper"); if (mapperModel != null) { mapperModel.getConfig().put(GroupMapperConfig.MODE, mode.toString()); updateGroupMapperConfigOptions(mapperModel, otherConfigOptions); realm.updateUserFederationMapper(mapperModel); } else { String baseDn = providerModel.getConfig().get(LDAPConstants.BASE_DN); mapperModel = KeycloakModelUtils.createUserFederationMapperModel( "groupsMapper", providerModel.getId(), GroupLDAPFederationMapperFactory.PROVIDER_ID, GroupMapperConfig.GROUPS_DN, "ou=Groups," + baseDn, GroupMapperConfig.MAPPED_GROUP_ATTRIBUTES, descriptionAttrName, GroupMapperConfig.PRESERVE_GROUP_INHERITANCE, "true", GroupMapperConfig.MODE, mode.toString()); updateGroupMapperConfigOptions(mapperModel, otherConfigOptions); realm.addUserFederationMapper(mapperModel); } }
@Override public void updateCredentialDirectly(UserCredentialValueModel credModel) { CredentialEntity credentialEntity = getCredentialEntity(user, credModel.getType()); if (credentialEntity == null) { credentialEntity = new CredentialEntity(); credentialEntity.setId(KeycloakModelUtils.generateId()); credentialEntity.setType(credModel.getType()); credentialEntity.setCreatedDate(credModel.getCreatedDate()); credentialEntity.setUser(user); em.persist(credentialEntity); user.getCredentials().add(credentialEntity); } credentialEntity.setValue(credModel.getValue()); credentialEntity.setSalt(credModel.getSalt()); credentialEntity.setDevice(credModel.getDevice()); credentialEntity.setHashIterations(credModel.getHashIterations()); credentialEntity.setCounter(credModel.getCounter()); credentialEntity.setAlgorithm(credModel.getAlgorithm()); credentialEntity.setDigits(credModel.getDigits()); credentialEntity.setPeriod(credModel.getPeriod()); em.flush(); }
@Override public void preprocessFederatedIdentity( KeycloakSession session, RealmModel realm, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) { String template = mapperModel.getConfig().get(TEMPLATE); Matcher m = substitution.matcher(template); StringBuffer sb = new StringBuffer(); while (m.find()) { String variable = m.group(1); if (variable.equals("ALIAS")) { m.appendReplacement(sb, context.getIdpConfig().getAlias()); } else if (variable.equals("UUID")) { m.appendReplacement(sb, KeycloakModelUtils.generateId()); } else if (variable.startsWith("CLAIM.")) { String name = variable.substring("CLAIM.".length()); Object value = AbstractClaimMapper.getClaimValue(context, name); if (value == null) value = ""; m.appendReplacement(sb, value.toString()); } else { m.appendReplacement(sb, m.group(1)); } } m.appendTail(sb); String username = sb.toString(); context.setModelUsername(username); }
@Override public void loadPersistentSessions( final KeycloakSessionFactory sessionFactory, final int maxErrors, final int sessionsPerSegment) { log.debug("Start pre-loading userSessions and clientSessions from persistent storage"); KeycloakModelUtils.runJobInTransaction( sessionFactory, new KeycloakSessionTask() { @Override public void run(KeycloakSession session) { InfinispanConnectionProvider connections = session.getProvider(InfinispanConnectionProvider.class); Cache<String, Serializable> cache = connections.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME); InfinispanUserSessionInitializer initializer = new InfinispanUserSessionInitializer( sessionFactory, cache, new OfflineUserSessionLoader(), maxErrors, sessionsPerSegment, "offlineUserSessions"); initializer.initCache(); initializer.loadPersistentSessions(); } }); log.debug("Pre-loading userSessions and clientSessions from persistent storage finished"); }
public static void addOrUpdateRoleLDAPMappers( RealmModel realm, UserFederationProviderModel providerModel, RoleLDAPFederationMapper.Mode mode) { UserFederationMapperModel mapperModel = realm.getUserFederationMapperByName(providerModel.getId(), "realmRolesMapper"); if (mapperModel != null) { mapperModel.getConfig().put(RoleLDAPFederationMapper.MODE, mode.toString()); realm.updateUserFederationMapper(mapperModel); } else { String baseDn = providerModel.getConfig().get(LDAPConstants.BASE_DN); mapperModel = KeycloakModelUtils.createUserFederationMapperModel( "realmRolesMapper", providerModel.getId(), RoleLDAPFederationMapperFactory.PROVIDER_ID, RoleLDAPFederationMapper.ROLES_DN, "ou=RealmRoles," + baseDn, RoleLDAPFederationMapper.USE_REALM_ROLES_MAPPING, "true", RoleLDAPFederationMapper.MODE, mode.toString()); realm.addUserFederationMapper(mapperModel); } mapperModel = realm.getUserFederationMapperByName(providerModel.getId(), "financeRolesMapper"); if (mapperModel != null) { mapperModel.getConfig().put(RoleLDAPFederationMapper.MODE, mode.toString()); realm.updateUserFederationMapper(mapperModel); } else { String baseDn = providerModel.getConfig().get(LDAPConstants.BASE_DN); mapperModel = KeycloakModelUtils.createUserFederationMapperModel( "financeRolesMapper", providerModel.getId(), RoleLDAPFederationMapperFactory.PROVIDER_ID, RoleLDAPFederationMapper.ROLES_DN, "ou=FinanceRoles," + baseDn, RoleLDAPFederationMapper.USE_REALM_ROLES_MAPPING, "false", RoleLDAPFederationMapper.CLIENT_ID, "finance", RoleLDAPFederationMapper.MODE, mode.toString()); realm.addUserFederationMapper(mapperModel); } }
private CredentialEntity setCredentials(UserEntity user, UserCredentialModel cred) { CredentialEntity credentialEntity = new CredentialEntity(); credentialEntity.setId(KeycloakModelUtils.generateId()); credentialEntity.setType(cred.getType()); credentialEntity.setDevice(cred.getDevice()); credentialEntity.setUser(user); return credentialEntity; }
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); }
private String insertApplicationRole(DBCollection roles, String roleName, String applicationId) { BasicDBObject role = new BasicDBObject(); String roleId = KeycloakModelUtils.generateId(); role.append("_id", roleId); role.append("name", roleName); role.append("applicationId", applicationId); role.append("nameIndex", applicationId + "//" + roleName); roles.insert(role); return roleId; }
public AccessTokenResponseBuilder generateRefreshToken() { if (accessToken == null) { throw new IllegalStateException("accessToken not set"); } refreshToken = new RefreshToken(accessToken); refreshToken.id(KeycloakModelUtils.generateId()); refreshToken.issuedNow(); refreshToken.expiration(Time.currentTime() + realm.getSsoSessionIdleTimeout()); return this; }
@Override public void config( RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) { impersonatedUserId = manager .getSession() .users() .getUserByUsername("test-user@localhost", appRealm) .getId(); { UserModel masterImpersonator = manager.getSession().users().addUser(adminstrationRealm, "master-impersonator"); masterImpersonator.setEnabled(true); ClientModel adminRealmClient = adminstrationRealm.getClientByClientId( KeycloakModelUtils.getMasterRealmAdminApplicationClientId( appRealm.getName())); RoleModel masterImpersonatorRole = adminRealmClient.getRole(ImpersonationConstants.IMPERSONATION_ROLE); masterImpersonator.grantRole(masterImpersonatorRole); } { UserModel masterBadImpersonator = manager .getSession() .users() .addUser(adminstrationRealm, "master-bad-impersonator"); masterBadImpersonator.setEnabled(true); } { UserModel impersonator = manager.getSession().users().addUser(appRealm, "impersonator"); impersonator.setEnabled(true); ClientModel appRealmClient = appRealm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID); RoleModel realmImpersonatorRole = appRealmClient.getRole(ImpersonationConstants.IMPERSONATION_ROLE); impersonator.grantRole(realmImpersonatorRole); } { UserModel impersonator = manager.getSession().users().addUser(appRealm, "realm-admin"); impersonator.setEnabled(true); ClientModel appRealmClient = appRealm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID); RoleModel realmImpersonatorRole = appRealmClient.getRole(AdminRoles.REALM_ADMIN); impersonator.grantRole(realmImpersonatorRole); } { UserModel badimpersonator = manager.getSession().users().addUser(appRealm, "bad-impersonator"); badimpersonator.setEnabled(true); } }
@Override public Scope create(final String name, final ResourceServer resourceServer) { ScopeEntity entity = new ScopeEntity(); entity.setId(KeycloakModelUtils.generateId()); entity.setName(name); entity.setResourceServerId(resourceServer.getId()); getMongoStore().insertEntity(entity, getInvocationContext()); return new ScopeAdapter(entity, getInvocationContext(), this.authorizationProvider); }
@Override public void importNewUser( KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) { String roleName = mapperModel.getConfig().get(ConfigConstants.ROLE); RoleModel role = KeycloakModelUtils.getRoleFromString(realm, roleName); if (role == null) throw new IdentityBrokerException("Unable to find role: " + roleName); user.grantRole(role); }
@GET @Path("group-by-path/{path: .*}") @NoCache @Produces(MediaType.APPLICATION_JSON) public GroupRepresentation getGroupByPath(@PathParam("path") String path) { auth.requireView(); GroupModel found = KeycloakModelUtils.findGroupByPath(realm, path); if (found == null) { throw new NotFoundException("Group path does not exist"); } return ModelToRepresentation.toGroupHierarchy(found, true); }
@Override public Policy create(String name, String type, ResourceServer resourceServer) { PolicyEntity entity = new PolicyEntity(); entity.setId(KeycloakModelUtils.generateId()); entity.setName(name); entity.setType(type); entity.setResourceServerId(resourceServer.getId()); getMongoStore().insertEntity(entity, getInvocationContext()); return new PolicyAdapter(entity, getInvocationContext(), this.authorizationProvider); }
@Override public void setUsername(String username) { username = KeycloakModelUtils.toLowerCaseSafe(username); if (getUsername() == null) { user.setUsername(username); return; } if (getUsername().equals(username)) return; // allow setting to same name if (inMemoryModel.hasUserWithUsername(realm.getId(), username)) throw new ModelDuplicateException( "User with username " + username + " already exists in realm."); user.setUsername(username); }
@Override public void setEmail(String email) { email = KeycloakModelUtils.toLowerCaseSafe(email); if (email == null) { user.setEmail(email); return; } if (email.equals(getEmail())) return; RealmAdapter realmAdapter = (RealmAdapter) realm; if (realmAdapter.hasUserWithEmail(email)) throw new ModelDuplicateException("User with email address " + email + " already exists."); user.setEmail(email); }
/** * Generate a new secret for the client * * @return */ @Path("client-secret") @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public CredentialRepresentation regenerateSecret() { auth.requireManage(); if (client == null) { throw new NotFoundException("Could not find client"); } logger.debug("regenerateSecret"); UserCredentialModel cred = KeycloakModelUtils.generateSecret(client); CredentialRepresentation rep = ModelToRepresentation.toRepresentation(cred); adminEvent.operation(OperationType.ACTION).resourcePath(uriInfo).representation(rep).success(); return rep; }
@Override public void addConsent(UserConsentModel consent) { String clientId = consent.getClient().getId(); UserConsentEntity consentEntity = getGrantedConsentEntity(clientId); if (consentEntity != null) { throw new ModelDuplicateException( "Consent already exists for client [" + clientId + "] and user [" + user.getId() + "]"); } consentEntity = new UserConsentEntity(); consentEntity.setId(KeycloakModelUtils.generateId()); consentEntity.setUser(user); consentEntity.setClientId(clientId); em.persist(consentEntity); em.flush(); updateGrantedConsentEntity(consentEntity, consent); }
public AccessTokenResponseBuilder generateIDToken() { if (accessToken == null) { throw new IllegalStateException("accessToken not set"); } idToken = new IDToken(); idToken.id(KeycloakModelUtils.generateId()); idToken.subject(accessToken.getSubject()); idToken.audience(client.getClientId()); idToken.issuedNow(); idToken.issuedFor(accessToken.getIssuedFor()); idToken.issuer(accessToken.getIssuer()); idToken.setSessionState(accessToken.getSessionState()); if (realm.getAccessTokenLifespan() > 0) { idToken.expiration(Time.currentTime() + realm.getAccessTokenLifespan()); } transformIDToken( session, idToken, realm, client, userSession.getUser(), userSession, clientSession); return this; }
private void addDefaultMappers(KeycloakSession session, DBCollection clients) { DBCursor clientsCursor = clients.find(); try { while (clientsCursor.hasNext()) { BasicDBObject currentClient = (BasicDBObject) clientsCursor.next(); BasicDBList dbProtocolMappers = new BasicDBList(); currentClient.put("protocolMappers", dbProtocolMappers); Object claimMask = currentClient.get("allowedClaimsMask"); MigrationProvider migrationProvider = session.getProvider(MigrationProvider.class); List<ProtocolMapperRepresentation> protocolMappers = migrationProvider.getMappersForClaimMask((Long) claimMask); for (ProtocolMapperRepresentation protocolMapper : protocolMappers) { BasicDBObject dbMapper = new BasicDBObject(); dbMapper.put("id", KeycloakModelUtils.generateId()); dbMapper.put("protocol", protocolMapper.getProtocol()); dbMapper.put("name", protocolMapper.getName()); dbMapper.put("consentRequired", protocolMapper.isConsentRequired()); dbMapper.put("consentText", protocolMapper.getConsentText()); dbMapper.put("protocolMapper", protocolMapper.getProtocolMapper()); Map<String, String> config = protocolMapper.getConfig(); BasicDBObject dbConfig = MapMapper.convertMap(config); dbMapper.put("config", dbConfig); dbProtocolMappers.add(dbMapper); } // Remove obsolete keys from client currentClient.remove("allowedClaimsMask"); log.debugv("Added default mappers to application {1}", currentClient.get("name")); clients.save(currentClient); } } finally { clientsCursor.close(); } }
public static UserFederationMapperModel addUserAttributeMapper( RealmModel realm, UserFederationProviderModel providerModel, String mapperName, String userModelAttributeName, String ldapAttributeName) { UserFederationMapperModel mapperModel = KeycloakModelUtils.createUserFederationMapperModel( mapperName, providerModel.getId(), UserAttributeLDAPFederationMapperFactory.PROVIDER_ID, UserAttributeLDAPFederationMapper.USER_MODEL_ATTRIBUTE, userModelAttributeName, UserAttributeLDAPFederationMapper.LDAP_ATTRIBUTE, ldapAttributeName, UserAttributeLDAPFederationMapper.READ_ONLY, "false", UserAttributeLDAPFederationMapper.ALWAYS_READ_VALUE_FROM_LDAP, "false", UserAttributeLDAPFederationMapper.IS_MANDATORY_IN_LDAP, "false"); return realm.addUserFederationMapper(mapperModel); }
@Override public AccessToken transformAccessToken( AccessToken token, ProtocolMapperModel mappingModel, KeycloakSession session, UserSessionModel userSession, ClientSessionModel clientSession) { String role = mappingModel.getConfig().get(ROLE_CONFIG); String[] scopedRole = KeycloakModelUtils.parseRole(role); String appName = scopedRole[0]; String roleName = scopedRole[1]; if (appName != null) { token.addAccess(appName).addRole(roleName); } else { AccessToken.Access access = token.getRealmAccess(); if (access == null) { access = new AccessToken.Access(); token.setRealmAccess(access); } access.addRole(role); } return token; }
private void addAdminRole( String roleName, String realmId, String applicationId, String realmAdminAppRoleId) { String roleTableName = database.correctObjectName("KEYCLOAK_ROLE", Table.class); String compositeRoleTableName = database.correctObjectName("COMPOSITE_ROLE", Table.class); String newRoleId = KeycloakModelUtils.generateId(); InsertStatement insertRole = new InsertStatement(null, null, roleTableName) .addColumnValue("ID", newRoleId) .addColumnValue("APP_REALM_CONSTRAINT", applicationId) .addColumnValue("APPLICATION_ROLE", true) .addColumnValue("NAME", roleName) .addColumnValue("REALM_ID", realmId) .addColumnValue("APPLICATION", applicationId); // Add newly created role to the composite roles of 'realm-admin' role InsertStatement insertCompRole = new InsertStatement(null, null, compositeRoleTableName) .addColumnValue("COMPOSITE", realmAdminAppRoleId) .addColumnValue("CHILD_ROLE", newRoleId); statements.add(insertRole); statements.add(insertCompRole); }
@Override public boolean hasRole(RoleModel role) { Set<RoleModel> roles = getRoleMappings(); return KeycloakModelUtils.hasRole(roles, role); }
private List<ComponentModel> getMappers() { List<ComponentModel> result = new LinkedList<>(); ComponentModel mapperModel = KeycloakModelUtils.createComponentModel( "first name", "fed-provider", UserAttributeLDAPStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(), UserAttributeLDAPStorageMapper.USER_MODEL_ATTRIBUTE, UserModel.FIRST_NAME, UserAttributeLDAPStorageMapper.LDAP_ATTRIBUTE, LDAPConstants.GIVENNAME, UserAttributeLDAPStorageMapper.READ_ONLY, "true", UserAttributeLDAPStorageMapper.ALWAYS_READ_VALUE_FROM_LDAP, "true", UserAttributeLDAPStorageMapper.IS_MANDATORY_IN_LDAP, "true"); mapperModel.setId("idd1"); result.add(mapperModel); mapperModel = KeycloakModelUtils.createComponentModel( "username-cn", "fed-provider", UserAttributeLDAPStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(), UserAttributeLDAPStorageMapper.USER_MODEL_ATTRIBUTE, UserModel.USERNAME, UserAttributeLDAPStorageMapper.LDAP_ATTRIBUTE, LDAPConstants.CN, UserAttributeLDAPStorageMapper.READ_ONLY, "true", UserAttributeLDAPStorageMapper.ALWAYS_READ_VALUE_FROM_LDAP, "false", UserAttributeLDAPStorageMapper.IS_MANDATORY_IN_LDAP, "true"); mapperModel.setId("idd2"); result.add(mapperModel); mapperModel = KeycloakModelUtils.createComponentModel( "full name", "fed-provider", FullNameLDAPStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(), FullNameLDAPStorageMapper.LDAP_FULL_NAME_ATTRIBUTE, LDAPConstants.CN, UserAttributeLDAPStorageMapper.READ_ONLY, "true"); mapperModel.setId("idd3"); result.add(mapperModel); mapperModel = KeycloakModelUtils.createComponentModel( "sAMAccountName", "fed-provider", UserAttributeLDAPStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(), UserAttributeLDAPStorageMapper.USER_MODEL_ATTRIBUTE, UserModel.USERNAME, UserAttributeLDAPStorageMapper.LDAP_ATTRIBUTE, LDAPConstants.SAM_ACCOUNT_NAME, UserAttributeLDAPStorageMapper.READ_ONLY, "false", UserAttributeLDAPStorageMapper.ALWAYS_READ_VALUE_FROM_LDAP, "false", UserAttributeLDAPStorageMapper.IS_MANDATORY_IN_LDAP, "true"); mapperModel.setId("idd4"); result.add(mapperModel); return result; }
private void convertSocialToIdFedRealms() { DBCollection realms = db.getCollection("realms"); DBCursor realmsCursor = realms.find(); try { while (realmsCursor.hasNext()) { BasicDBObject realm = (BasicDBObject) realmsCursor.next(); boolean updateProfileOnInitialSocialLogin = realm.getBoolean("updateProfileOnInitialSocialLogin"); BasicDBObject socialConfig = (BasicDBObject) realm.get("socialConfig"); BasicDBList identityProviders = (BasicDBList) realm.get("identityProviders"); if (identityProviders == null) { identityProviders = new BasicDBList(); realm.put("identityProviders", identityProviders); } if (socialConfig != null) { for (Map.Entry<String, Object> entry : socialConfig.entrySet()) { if (entry.getKey().endsWith("###key")) { String socialProviderId = entry.getKey().substring(0, entry.getKey().indexOf("###")); String clientId = (String) entry.getValue(); String clientSecret = socialConfig.getString(socialProviderId + "###secret"); DBObject identityProviderConfig = new BasicDBObjectBuilder() .add("clientId", clientId) .add("clientSecret", clientSecret) .get(); DBObject identityProvider = new BasicDBObjectBuilder() .add("internalId", KeycloakModelUtils.generateId()) .add("providerId", socialProviderId) .add("alias", socialProviderId) .add("updateProfileFirstLogin", updateProfileOnInitialSocialLogin) .add("enabled", true) .add("storeToken", false) .add("authenticateByDefault", false) .add("config", identityProviderConfig) .get(); identityProviders.add(identityProvider); log.debugv("Converted social provider {0} to identity provider", socialProviderId); } } } // Remove obsolete keys from realm realm.remove("social"); realm.remove("updateProfileOnInitialSocialLogin"); realm.remove("socialConfig"); // Update realm in DB now realms.save(realm); log.debugv( "Social providers of realm {0} converted to identity providers", realm.get("_id")); } } finally { realmsCursor.close(); } }