Package org.keycloak.models.utils
Class KeycloakModelUtils
- java.lang.Object
- 
- org.keycloak.models.utils.KeycloakModelUtils
 
- 
 public final class KeycloakModelUtils extends Object Set of helper methods, which are useful in various model implementations.- Author:
- Marek Posolda, Daniel Fesenmeyer
 
- 
- 
Field SummaryFields Modifier and Type Field Description static StringAUTH_TYPE_CLIENT_SECRETstatic StringAUTH_TYPE_CLIENT_SECRET_JWTstatic StringGROUP_PATH_SEPARATOR
 - 
Method SummaryAll Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static StringbuildGroupPath(GroupModel group)static StringbuildGroupPath(GroupModel group, GroupModel otherParentGroup)static StringbuildRoleQualifier(String clientId, String roleName)static Function<KeycloakSessionFactory,ComponentModel>componentModelGetter(String realmId, String componentId)static StringconvertClientScopeName(String previousName)Replace spaces in the name with underscore, so that scope name can be used as value of scope parameterstatic ComponentModelcreateComponentModel(String name, String parentId, String providerId, String providerType, String... config)static ClientModelcreateManagementClient(RealmModel realm, String name)static ClientModelcreatePublicClient(RealmModel realm, String name)static voiddeepFindAuthenticationExecutions(RealmModel realm, AuthenticationFlowModel flow, List<AuthenticationExecutionModel> result)Recursively find all AuthenticationExecutionModel from specified flow or all it's subflowsstatic ClientScopeModelfindClientScopeById(RealmModel realm, ClientModel client, String clientScopeId)Lookup clientScope OR client by id.static GroupModelfindGroupByPath(RealmModel realm, String path)static UserModelfindUserByNameOrEmail(KeycloakSession session, RealmModel realm, String username)Try to find user by username or email for authenticationstatic StringgenerateCodeSecret()static StringgenerateId()static CertificateRepresentationgenerateKeyPairCertificate(String subject)static StringgenerateSecret(ClientModel client)static X509CertificategetCertificate(String cert)static ClientScopeModelgetClientScopeByName(RealmModel realm, String clientScopeName)static Set<RoleModel>getClientScopeMappings(ClientModel client, ScopeContainerModel container)Deprecated.UsegetClientScopeMappingsStream(ClientModel, ScopeContainerModel)getClientScopeMappingsStream} instead.static Stream<RoleModel>getClientScopeMappingsStream(ClientModel client, ScopeContainerModel container)static <T extends Provider>
 ProviderFactory<T>getComponentFactory(KeycloakSessionFactory factory, Class<T> providerClass, Config.Scope config, String spiName)static ComponentModelgetComponentModel(KeycloakSessionFactory factory, String realmId, String componentId)static StringgetDefaultClientAuthenticatorType()static StringgetIdentityProviderDisplayName(KeycloakSession session, IdentityProviderModel provider)static StringgetMasterRealmAdminApplicationClientId(String realmName)static StringgetPemFromCertificate(X509Certificate certificate)static StringgetPemFromKey(Key key)static PrivateKeygetPrivateKey(String privateKeyPem)static PublicKeygetPublicKey(String publicKeyPem)static RoleModelgetRoleFromString(RealmModel realm, String roleName)static KeygetSecretKey(String secret)static intgetSecretLengthByAuthenticationType(String clientAuthenticatorType, String signingAlg)static booleanisExceptionRetriable(Throwable exception)Checks if the specified exception is retriable or not.static booleanisFlowUsed(RealmModel realm, AuthenticationFlowModel model)Check to see if a flow is currently in usestatic booleanisRealmProviderJpa(KeycloakSession session)static booleanisUsernameCaseSensitive(RealmModel realm)Returnstrueif given realm has attributeConstants.REALM_ATTR_USERNAME_CASE_SENSITIVEset and its value istrue.static StringnormalizeGroupPath(String groupPath)static String[]parseRole(String role)static Collection<String>resolveAttribute(GroupModel group, String name, boolean aggregateAttrs)static Collection<String>resolveAttribute(UserModel user, String name, boolean aggregateAttrs)static StringresolveFirstAttribute(GroupModel group, String name)static <V> VrunJobInRetriableTransaction(KeycloakSessionFactory factory, KeycloakSessionTaskWithResult<V> callable, int attemptsCount, int retryIntervalMillis)Creates a newKeycloakSessionand runs the specified callable in a new transaction.static voidrunJobInTransaction(KeycloakSessionFactory factory, KeycloakSessionTask task)Wrap given runnable job into KeycloakTransaction.static <V> VrunJobInTransactionWithResult(KeycloakSessionFactory factory, KeycloakSessionTaskWithResult<V> callable)Wrap a given callable job into a KeycloakTransaction.static voidrunJobInTransactionWithTimeout(KeycloakSessionFactory factory, KeycloakSessionTask task, int timeoutInSeconds)Wrap given runnable job into KeycloakTransaction.static booleansearchFor(RoleModel role, RoleModel composite, Set<String> visited)Deep search if given role is descendant of composite rolestatic voidsetTransactionLimit(KeycloakSessionFactory factory, int timeoutInSeconds)static voidsetupAuthorizationServices(RealmModel realm)static voidsetupDefaultRole(RealmModel realm, String defaultRoleName)Creates default role for particular realm with the given name.static voidsetupDeleteAccount(ClientModel accountClient)static RoleModelsetupOfflineRole(RealmModel realm)static voidsuspendJtaTransaction(KeycloakSessionFactory factory, Runnable runnable)static StringtoLowerCaseSafe(String str)
 
- 
- 
- 
Field Detail- 
AUTH_TYPE_CLIENT_SECRETpublic static final String AUTH_TYPE_CLIENT_SECRET - See Also:
- Constant Field Values
 
 - 
AUTH_TYPE_CLIENT_SECRET_JWTpublic static final String AUTH_TYPE_CLIENT_SECRET_JWT - See Also:
- Constant Field Values
 
 - 
GROUP_PATH_SEPARATORpublic static final String GROUP_PATH_SEPARATOR - See Also:
- Constant Field Values
 
 
- 
 - 
Method Detail- 
generateIdpublic static String generateId() 
 - 
getCertificatepublic static X509Certificate getCertificate(String cert) 
 - 
getPrivateKeypublic static PrivateKey getPrivateKey(String privateKeyPem) 
 - 
getPemFromCertificatepublic static String getPemFromCertificate(X509Certificate certificate) 
 - 
generateKeyPairCertificatepublic static CertificateRepresentation generateKeyPairCertificate(String subject) 
 - 
generateSecretpublic static String generateSecret(ClientModel client) 
 - 
getDefaultClientAuthenticatorTypepublic static String getDefaultClientAuthenticatorType() 
 - 
generateCodeSecretpublic static String generateCodeSecret() 
 - 
createManagementClientpublic static ClientModel createManagementClient(RealmModel realm, String name) 
 - 
createPublicClientpublic static ClientModel createPublicClient(RealmModel realm, String name) 
 - 
searchForpublic static boolean searchFor(RoleModel role, RoleModel composite, Set<String> visited) Deep search if given role is descendant of composite role- Parameters:
- role- role to check
- composite- composite role
- visited- set of already visited roles (used for recursion)
- Returns:
- true if "role" is descendant of "composite"
 
 - 
findUserByNameOrEmailpublic static UserModel findUserByNameOrEmail(KeycloakSession session, RealmModel realm, String username) Try to find user by username or email for authentication- Parameters:
- realm- realm
- username- username or email of user
- Returns:
- found user
 
 - 
runJobInTransactionpublic static void runJobInTransaction(KeycloakSessionFactory factory, KeycloakSessionTask task) Wrap given runnable job into KeycloakTransaction.
 - 
runJobInTransactionWithResultpublic static <V> V runJobInTransactionWithResult(KeycloakSessionFactory factory, KeycloakSessionTaskWithResult<V> callable) Wrap a given callable job into a KeycloakTransaction.
 - 
runJobInRetriableTransactionpublic static <V> V runJobInRetriableTransaction(KeycloakSessionFactory factory, KeycloakSessionTaskWithResult<V> callable, int attemptsCount, int retryIntervalMillis) Creates a newKeycloakSessionand runs the specified callable in a new transaction. If the transaction fails with a SQL retriable error, the method re-executes the specified callable until it either succeeds or the maximum number of attempts is reached, leaving some increasing random delay milliseconds between the invocations. It uses the exponential backoff + jitter algorithm to compute the delay, which is limited toattemptsCount * retryIntervalMillis. More details https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/- Type Parameters:
- V- the type returned by the callable.
- Parameters:
- factory- a reference to the- KeycloakSessionFactory.
- callable- a reference to the- KeycloakSessionTaskWithResultthat will be executed in a retriable way.
- attemptsCount- the maximum number of attempts to execute the callable.
- retryIntervalMillis- the base interval value in millis used to compute the delay.
- Returns:
- the value computed by the callable.
 
 - 
isExceptionRetriablepublic static boolean isExceptionRetriable(Throwable exception) Checks if the specified exception is retriable or not. A retriable exception must be an instance ofSQLExceptionand must have a 40001 SQL retriable state. This is a standard SQL state as defined in SQL standard, and across the implementations its meaning boils down to "deadlock" (applies to Postgres, MSSQL, Oracle, MySQL, and others).- Parameters:
- exception- the exception to be checked.
- Returns:
- trueif the exception is retriable;- falseotherwise.
 
 - 
runJobInTransactionWithTimeoutpublic static void runJobInTransactionWithTimeout(KeycloakSessionFactory factory, KeycloakSessionTask task, int timeoutInSeconds) Wrap given runnable job into KeycloakTransaction. Set custom timeout for the JTA transaction (in case we're in the environment with JTA enabled)- Parameters:
- factory-
- task-
- timeoutInSeconds-
 
 - 
setTransactionLimitpublic static void setTransactionLimit(KeycloakSessionFactory factory, int timeoutInSeconds) 
 - 
componentModelGetterpublic static Function<KeycloakSessionFactory,ComponentModel> componentModelGetter(String realmId, String componentId) 
 - 
getComponentModelpublic static ComponentModel getComponentModel(KeycloakSessionFactory factory, String realmId, String componentId) 
 - 
getComponentFactorypublic static <T extends Provider> ProviderFactory<T> getComponentFactory(KeycloakSessionFactory factory, Class<T> providerClass, Config.Scope config, String spiName) 
 - 
getMasterRealmAdminApplicationClientIdpublic static String getMasterRealmAdminApplicationClientId(String realmName) 
 - 
createComponentModelpublic static ComponentModel createComponentModel(String name, String parentId, String providerId, String providerType, String... config) 
 - 
setupDefaultRolepublic static void setupDefaultRole(RealmModel realm, String defaultRoleName) Creates default role for particular realm with the given name.- Parameters:
- realm- Realm
- defaultRoleName- Name of the newly created defaultRole
 
 - 
setupOfflineRolepublic static RoleModel setupOfflineRole(RealmModel realm) 
 - 
setupDeleteAccountpublic static void setupDeleteAccount(ClientModel accountClient) 
 - 
deepFindAuthenticationExecutionspublic static void deepFindAuthenticationExecutions(RealmModel realm, AuthenticationFlowModel flow, List<AuthenticationExecutionModel> result) Recursively find all AuthenticationExecutionModel from specified flow or all it's subflows- Parameters:
- realm-
- flow-
- result- input should be empty list. At the end will be all executions added to this list
 
 - 
resolveFirstAttributepublic static String resolveFirstAttribute(GroupModel group, String name) 
 - 
resolveAttributepublic static Collection<String> resolveAttribute(GroupModel group, String name, boolean aggregateAttrs) 
 - 
resolveAttributepublic static Collection<String> resolveAttribute(UserModel user, String name, boolean aggregateAttrs) 
 - 
findGroupByPathpublic static GroupModel findGroupByPath(RealmModel realm, String path) 
 - 
buildGroupPathpublic static String buildGroupPath(GroupModel group) 
 - 
buildGroupPathpublic static String buildGroupPath(GroupModel group, GroupModel otherParentGroup) 
 - 
getClientScopeMappings@Deprecated public static Set<RoleModel> getClientScopeMappings(ClientModel client, ScopeContainerModel container) Deprecated.UsegetClientScopeMappingsStream(ClientModel, ScopeContainerModel)getClientScopeMappingsStream} instead.- Parameters:
- client-- ClientModel
- container-- ScopeContainerModel
- Returns:
 
 - 
getClientScopeMappingsStreampublic static Stream<RoleModel> getClientScopeMappingsStream(ClientModel client, ScopeContainerModel container) 
 - 
getRoleFromStringpublic static RoleModel getRoleFromString(RealmModel realm, String roleName) 
 - 
isFlowUsedpublic static boolean isFlowUsed(RealmModel realm, AuthenticationFlowModel model) Check to see if a flow is currently in use- Parameters:
- realm-
- model-
- Returns:
 
 - 
getClientScopeByNamepublic static ClientScopeModel getClientScopeByName(RealmModel realm, String clientScopeName) 
 - 
findClientScopeByIdpublic static ClientScopeModel findClientScopeById(RealmModel realm, ClientModel client, String clientScopeId) Lookup clientScope OR client by id. Method is useful if you know just ID, but you don't know if underlying model is clientScope or client
 - 
convertClientScopeNamepublic static String convertClientScopeName(String previousName) Replace spaces in the name with underscore, so that scope name can be used as value of scope parameter
 - 
setupAuthorizationServicespublic static void setupAuthorizationServices(RealmModel realm) 
 - 
suspendJtaTransactionpublic static void suspendJtaTransaction(KeycloakSessionFactory factory, Runnable runnable) 
 - 
getIdentityProviderDisplayNamepublic static String getIdentityProviderDisplayName(KeycloakSession session, IdentityProviderModel provider) 
 - 
isRealmProviderJpapublic static boolean isRealmProviderJpa(KeycloakSession session) - Returns:
- true if implementation of realmProvider is "jpa" . Which is always the case in standard Keycloak installations.
 
 - 
getSecretLengthByAuthenticationTypepublic static int getSecretLengthByAuthenticationType(String clientAuthenticatorType, String signingAlg) - Parameters:
- clientAuthenticatorType-
- Returns:
- secret size based on authentication type
 
 - 
isUsernameCaseSensitivepublic static boolean isUsernameCaseSensitive(RealmModel realm) Returnstrueif given realm has attributeConstants.REALM_ATTR_USERNAME_CASE_SENSITIVEset and its value istrue. Otherwise default value of it is returned. The default setting can be seen atConstants.REALM_ATTR_USERNAME_CASE_SENSITIVE_DEFAULT.- Parameters:
- realm-
- Returns:
- See the description
- Throws:
- NullPointerException- if- realmis- null
 
 
- 
 
-