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(boolean escapeSlashes, String... names) static 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 voiddeepDeleteAuthenticationExecutor(KeycloakSession session, RealmModel realm, AuthenticationExecutionModel authExecutor, Runnable flowUnavailableHandler, Runnable builtinFlowHandler) Recursively remove authentication executor (including sub-flows and configs) from the model storagestatic voiddeepDeleteAuthenticationFlow(KeycloakSession session, 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 booleanescapeSlashesInGroupPath(KeycloakSession session) Helper to get from the session if group path slashes should be escaped or not.static ClientScopeModelfindClientScopeById(RealmModel realm, ClientModel client, String clientScopeId) Lookup clientScope OR client by id.static GroupModelfindGroupByPath(KeycloakSession session, RealmModel realm, String path) Finds group by path.static GroupModelfindGroupByPath(KeycloakSession session, RealmModel realm, String[] path) Finds group by path.static UserModelfindUserByNameOrEmail(KeycloakSession session, RealmModel realm, String username) If "Login with email" is enabled and the given username contains '@', attempts to find the user by email for authentication.static Stringstatic StringReturn an ID generated using the UUID java class.static CertificateRepresentationgenerateKeyPairCertificate(String subject) static CertificateRepresentationgenerateKeyPairCertificate(String subject, int keysize, Calendar endDate) static StringgenerateSecret(ClientModel client) static StringReturn an ID generated using the UUID class but using base64 URL encoding with the two longs (msb+lsb).static StringgenerateShortId(UUID uuid) Generates a short ID representation for the UUID.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 StringgetMasterRealmAdminManagementClientId(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 booleanisFlowUsed(KeycloakSession session, RealmModel realm, AuthenticationFlowModel model) Check to see if a flow is currently in usestatic booleanisValidUUID(String uuid) Check if a string is a valid UUID.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 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, String taskName) 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 <T> TrunOnRealm(KeycloakSession session, RealmModel target, Function<KeycloakSession, T> operation) Runs the givenoperationwithin the scope of the given @{target} realm.static booleanDeep search if given role is descendant of composite rolestatic voidsetDefaultGroups(KeycloakSession session, RealmModel realm, Stream<String> groups) Sets the default groups on the realmstatic 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 String[]Splits a group path than can be escaped for slashes.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:
-
GROUP_PATH_ESCAPE
- See Also:
-
MAX_CLIENT_LOOKUPS_DURING_ROLE_RESOLVE
public static final int MAX_CLIENT_LOOKUPS_DURING_ROLE_RESOLVE- See Also:
-
DEFAULT_RSA_KEY_SIZE
public static final int DEFAULT_RSA_KEY_SIZE- See Also:
-
DEFAULT_CERTIFICATE_VALIDITY_YEARS
public static final int DEFAULT_CERTIFICATE_VALIDITY_YEARS- See Also:
-
-
Method Details
-
generateId
Return an ID generated using the UUID java class.- Returns:
- The ID using UUID.toString (36 chars)
-
generateShortId
Return an ID generated using the UUID class but using base64 URL encoding with the two longs (msb+lsb).- Returns:
- The ID getting msb and lsb from UUID and encoding them in base64 URL without padding (22 chars)
-
generateShortId
Generates a short ID representation for the UUID. The representation is the base64 url encoding of the msb+lsb of the UUID.- Parameters:
uuid- The UUID to represent- Returns:
- The string representation in 22 characters
-
isValidUUID
Check if a string is a valid UUID.- Parameters:
uuid- The UUID string to verify- Returns:
- true if the string is a valid uuid
-
getPublicKey
-
getCertificate
-
getPrivateKey
-
getSecretKey
-
getPemFromKey
-
getPemFromCertificate
-
generateKeyPairCertificate
-
generateKeyPairCertificate
public static CertificateRepresentation generateKeyPairCertificate(String subject, int keysize, Calendar endDate) -
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) If "Login with email" is enabled and the given username contains '@', attempts to find the user by email for authentication. Otherwise, or if not found, attempts to find the user by username.- Parameters:
realm- the realm to search withinusername- the username or email of the user- Returns:
- the found user if present; otherwise,
null
-
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, String taskName) 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 executetaskName- Name of the task. Can be useful for logging purposes- Returns:
- The return value from the callable
-
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) -
getMasterRealmAdminManagementClientId
-
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) -
escapeSlashesInGroupPath
Helper to get from the session if group path slashes should be escaped or not.- Parameters:
session- The session- Returns:
- true or false
-
findGroupByPath
Finds group by path. Path is separated by '/' character. For example: /group/subgroup/subsubgroup The method takes into consideration also groups with '/' in their name. For example: /group/sub/group/subgroup This method allows escaping of slashes for example: /parent\/group/child which is a two level path for ["parent/group", "child"].- Parameters:
session- Keycloak sessionrealm- The realmpath- Path that will be searched among groups- Returns:
GroupModelcorresponding to the givenpathornullif no group was found
-
findGroupByPath
Finds group by path. Variant when you have the path already separated by group names.- Parameters:
session- Keycloak sessionrealm- The realmpath- Path The path hierarchy of groups- Returns:
GroupModelcorresponding to the givenpathornullif no group was found
-
splitPath
Splits a group path than can be escaped for slashes.- Parameters:
path- The group pathescapedSlashes- true if slashes are escaped in the path- Returns:
-
buildGroupPath
-
buildGroupPath
-
buildGroupPath
-
normalizeGroupPath
-
getClientScopeMappingsStream
public static Stream<RoleModel> getClientScopeMappingsStream(ClientModel client, ScopeContainerModel container) -
getRoleFromString
-
parseRole
-
buildRoleQualifier
-
isFlowUsed
public static boolean isFlowUsed(KeycloakSession session, RealmModel realm, AuthenticationFlowModel model) Check to see if a flow is currently in use- Parameters:
realm-model-- Returns:
-
deepDeleteAuthenticationFlow
public static void deepDeleteAuthenticationFlow(KeycloakSession session, RealmModel realm, AuthenticationFlowModel authFlow, Runnable flowUnavailableHandler, Runnable builtinFlowHandler) Recursively remove authentication flow (including all subflows and executions) from the model storage- Parameters:
session- The keycloak sessionrealm- The realmauthFlow- flow to deleteflowUnavailableHandler- Will be executed when flow, sub-flow or executor is nullbuiltinFlowHandler- will be executed when flow is built-in flow
-
deepDeleteAuthenticationExecutor
public static void deepDeleteAuthenticationExecutor(KeycloakSession session, RealmModel realm, AuthenticationExecutionModel authExecutor, Runnable flowUnavailableHandler, Runnable builtinFlowHandler) Recursively remove authentication executor (including sub-flows and configs) from the model storage- Parameters:
session- The keycloak sessionrealm- The realmauthExecutor- The authentication executor to removeflowUnavailableHandler- Handler that will be executed when flow, sub-flow or executor is nullbuiltinFlowHandler- Handler that 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) -
getSecretLengthByAuthenticationType
public static int getSecretLengthByAuthenticationType(String clientAuthenticatorType, String signingAlg) - Parameters:
clientAuthenticatorType-- Returns:
- secret size based on authentication type
-
setDefaultGroups
public static void setDefaultGroups(KeycloakSession session, RealmModel realm, Stream<String> groups) Sets the default groups on the realm- Parameters:
session-realm-groups-- Throws:
RuntimeException- if a group does not exist
-
runOnRealm
public static <T> T runOnRealm(KeycloakSession session, RealmModel target, Function<KeycloakSession, T> operation) Runs the given
operationwithin the scope of the given @{target} realm.Only use this method when you need to execute operations in a
RealmModelobject that is different than the one associated with thesession.- Parameters:
session- the sessiontarget- the target realmoperation- the operation- Returns:
- the result from the supplier
-
getAcceptedClientScopeProtocols
- Returns:
- the list of protocols accepted for the given client.
-