Package org.keycloak.models.utils
Class KeycloakModelUtils
java.lang.Object
org.keycloak.models.utils.KeycloakModelUtils
Set of helper methods, which are useful in various model implementations.
- Author:
- Marek Posolda, Daniel Fesenmeyer
-
Field Summary
Fields -
Method Summary
Modifier and TypeMethodDescriptionstatic StringbuildGroupPath(GroupModel group) static StringbuildGroupPath(GroupModel group, GroupModel otherParentGroup) static StringbuildRoleQualifier(String clientId, String roleName) static voidcloneContextRealmClientSessionToSession(KeycloakContext origContext, KeycloakSession targetSession) Sets up the context for the specified session with the RealmModel, clientModel and AuthenticatedSessionModel.static voidcloneContextRealmClientToSession(KeycloakContext origContext, KeycloakSession targetSession) Sets up the context for the specified session with the RealmModel.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 voiddeepDeleteAuthenticationFlow(RealmModel realm, AuthenticationFlowModel authFlow, Runnable flowUnavailableHandler, Runnable builtinFlowHandler) Recursively remove authentication flow (including all subflows and executions) from the model storagestatic 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(GroupProvider groupProvider, RealmModel realm, String path) static GroupModelfindGroupByPath(RealmModel realm, String path) Deprecated.static UserModelfindUserByNameOrEmail(KeycloakSession session, RealmModel realm, String username) Try to find user by username or email for authenticationstatic Stringstatic Stringstatic CertificateRepresentationgenerateKeyPairCertificate(String subject) static StringgenerateSecret(ClientModel client) static X509CertificategetCertificate(String cert) static ClientScopeModelgetClientScopeByName(RealmModel realm, String clientScopeName) 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 Stringstatic 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 booleanReturnstrueif given realm has attributeConstants.REALM_ATTR_USERNAME_CASE_SENSITIVEset and its value istrue.static StringnormalizeGroupPath(String groupPath) static String[]static Collection<String>resolveAttribute(GroupModel group, String name, boolean aggregateAttrs) static Collection<String>resolveAttribute(UserModel user, String name, boolean aggregateAttrs) 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, KeycloakContext context, KeycloakSessionTask task) Wrap given runnable job into KeycloakTransaction.static voidrunJobInTransaction(KeycloakSessionFactory factory, KeycloakSessionTask task) Wrap given runnable job into KeycloakTransaction.static <V> VrunJobInTransactionWithResult(KeycloakSessionFactory factory, KeycloakContext context, KeycloakSessionTaskWithResult<V> callable) Wrap a given callable job into a 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 booleanDeep search if given role is descendant of composite rolestatic voidsetTransactionLimit(KeycloakSessionFactory factory, int timeoutInSeconds) static voidstatic 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 Details
-
AUTH_TYPE_CLIENT_SECRET
- See Also:
-
AUTH_TYPE_CLIENT_SECRET_JWT
- See Also:
-
GROUP_PATH_SEPARATOR
- See Also:
-
-
Method Details
-
generateId
-
getPublicKey
-
getCertificate
-
getPrivateKey
-
getSecretKey
-
getPemFromKey
-
getPemFromCertificate
-
generateKeyPairCertificate
-
generateSecret
-
getDefaultClientAuthenticatorType
-
generateCodeSecret
-
createManagementClient
-
createPublicClient
-
searchFor
Deep search if given role is descendant of composite role- Parameters:
role- role to checkcomposite- composite rolevisited- set of already visited roles (used for recursion)- Returns:
- true if "role" is descendant of "composite"
-
findUserByNameOrEmail
public static UserModel findUserByNameOrEmail(KeycloakSession session, RealmModel realm, String username) Try to find user by username or email for authentication- Parameters:
realm- realmusername- username or email of user- Returns:
- found user
-
runJobInTransaction
Wrap given runnable job into KeycloakTransaction.- Parameters:
factory- The session factory to usetask- The task to execute
-
runJobInTransaction
public static void runJobInTransaction(KeycloakSessionFactory factory, KeycloakContext context, KeycloakSessionTask task) Wrap given runnable job into KeycloakTransaction.- Parameters:
factory- The session factory to usecontext- The context from the previous sessiontask- The task to execute
-
cloneContextRealmClientToSession
public static void cloneContextRealmClientToSession(KeycloakContext origContext, KeycloakSession targetSession) Sets up the context for the specified session with the RealmModel.- Parameters:
origContext- The original context to propagatetargetSession- The new target session to propagate the context to
-
cloneContextRealmClientSessionToSession
public static void cloneContextRealmClientSessionToSession(KeycloakContext origContext, KeycloakSession targetSession) Sets up the context for the specified session with the RealmModel, clientModel and AuthenticatedSessionModel.- Parameters:
origContext- The original context to propagatetargetSession- The new target session to propagate the context to
-
runJobInTransactionWithResult
public static <V> V runJobInTransactionWithResult(KeycloakSessionFactory factory, KeycloakSessionTaskWithResult<V> callable) Wrap a given callable job into a KeycloakTransaction.- Type Parameters:
V- The type for the result- Parameters:
factory- The session factorycallable- The callable to execute- Returns:
- The return value from the callable
-
runJobInTransactionWithResult
public static <V> V runJobInTransactionWithResult(KeycloakSessionFactory factory, KeycloakContext context, KeycloakSessionTaskWithResult<V> callable) Wrap a given callable job into a KeycloakTransaction.- Type Parameters:
V- The type for the result- Parameters:
factory- The session factorycontext- The context from the previous session to usecallable- The callable to execute- Returns:
- The return value from the callable
-
runJobInRetriableTransaction
public 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 theKeycloakSessionFactory.callable- a reference to theKeycloakSessionTaskWithResultthat 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.
-
isExceptionRetriable
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.
-
runJobInTransactionWithTimeout
public 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-
-
setTransactionLimit
-
componentModelGetter
public static Function<KeycloakSessionFactory,ComponentModel> componentModelGetter(String realmId, String componentId) -
getComponentModel
public static ComponentModel getComponentModel(KeycloakSessionFactory factory, String realmId, String componentId) -
getComponentFactory
public static <T extends Provider> ProviderFactory<T> getComponentFactory(KeycloakSessionFactory factory, Class<T> providerClass, Config.Scope config, String spiName) -
getMasterRealmAdminApplicationClientId
-
createComponentModel
-
toLowerCaseSafe
-
setupDefaultRole
Creates default role for particular realm with the given name.- Parameters:
realm- RealmdefaultRoleName- Name of the newly created defaultRole
-
setupOfflineRole
-
setupDeleteAccount
-
deepFindAuthenticationExecutions
public 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
-
resolveAttribute
public static Collection<String> resolveAttribute(GroupModel group, String name, boolean aggregateAttrs) -
resolveAttribute
public static Collection<String> resolveAttribute(UserModel user, String name, boolean aggregateAttrs) -
findGroupByPath
public static GroupModel findGroupByPath(GroupProvider groupProvider, RealmModel realm, String path) -
findGroupByPath
Deprecated.please usefindGroupByPath(GroupProvider, RealmModel, String)instead -
buildGroupPath
-
buildGroupPath
-
normalizeGroupPath
-
getClientScopeMappingsStream
public static Stream<RoleModel> getClientScopeMappingsStream(ClientModel client, ScopeContainerModel container) -
getRoleFromString
-
parseRole
-
buildRoleQualifier
-
isFlowUsed
Check to see if a flow is currently in use- Parameters:
realm-model-- Returns:
-
deepDeleteAuthenticationFlow
public static void deepDeleteAuthenticationFlow(RealmModel realm, AuthenticationFlowModel authFlow, Runnable flowUnavailableHandler, Runnable builtinFlowHandler) Recursively remove authentication flow (including all subflows and executions) from the model storage- Parameters:
realm-authFlow- flow to deleteflowUnavailableHandler- Will be executed when flow or some of it's subflow is nullbuiltinFlowHandler- will be executed when flow is built-in flow
-
getClientScopeByName
-
findClientScopeById
public 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 -
convertClientScopeName
Replace spaces in the name with underscore, so that scope name can be used as value of scope parameter -
setupAuthorizationServices
-
suspendJtaTransaction
-
getIdentityProviderDisplayName
public static String getIdentityProviderDisplayName(KeycloakSession session, IdentityProviderModel provider) -
isRealmProviderJpa
- Returns:
- true if implementation of realmProvider is "jpa" . Which is always the case in standard Keycloak installations.
-
getSecretLengthByAuthenticationType
public static int getSecretLengthByAuthenticationType(String clientAuthenticatorType, String signingAlg) - Parameters:
clientAuthenticatorType-- Returns:
- secret size based on authentication type
-
isUsernameCaseSensitive
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- ifrealmisnull
-
findGroupByPath(GroupProvider, RealmModel, String)instead