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 Details

  • Method Details

    • generateId

      public static String generateId()
      Return an ID generated using the UUID java class.
      Returns:
      The ID using UUID.toString (36 chars)
    • generateShortId

      public static String 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

      public static String generateShortId(UUID uuid)
      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
    • getPublicKey

      public static PublicKey getPublicKey(String publicKeyPem)
    • getCertificate

      public static X509Certificate getCertificate(String cert)
    • getPrivateKey

      public static PrivateKey getPrivateKey(String privateKeyPem)
    • getSecretKey

      public static Key getSecretKey(String secret)
    • getPemFromKey

      public static String getPemFromKey(Key key)
    • getPemFromCertificate

      public static String getPemFromCertificate(X509Certificate certificate)
    • generateKeyPairCertificate

      public static CertificateRepresentation generateKeyPairCertificate(String subject)
    • generateSecret

      public static String generateSecret(ClientModel client)
    • getDefaultClientAuthenticatorType

      public static String getDefaultClientAuthenticatorType()
    • generateCodeSecret

      public static String generateCodeSecret()
    • createManagementClient

      public static ClientModel createManagementClient(RealmModel realm, String name)
    • createPublicClient

      public static ClientModel createPublicClient(RealmModel realm, String name)
    • searchFor

      public 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"
    • findUserByNameOrEmail

      public 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
    • runJobInTransaction

      public static void runJobInTransaction(KeycloakSessionFactory factory, KeycloakSessionTask task)
      Wrap given runnable job into KeycloakTransaction.
      Parameters:
      factory - The session factory to use
      task - 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 use
      context - The context from the previous session
      task - 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 propagate
      targetSession - 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 propagate
      targetSession - 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 factory
      callable - The callable to execute
      Returns:
      The return value from the callable
    • runJobInTransactionWithResult

      public static <V> V runJobInTransactionWithResult(KeycloakSessionFactory factory, KeycloakContext context, KeycloakSessionTaskWithResult<V> callable, boolean useExistingSession, String taskName)
      Wrap a given callable job into a KeycloakTransaction.
      Type Parameters:
      V - The type for the result
      Parameters:
      factory - The session factory
      context - The context from the previous session to use
      callable - The callable to execute
      useExistingSession - if the existing session should be used
      taskName - 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

      public static void setTransactionLimit(KeycloakSessionFactory factory, int timeoutInSeconds)
    • 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

      public static String getMasterRealmAdminApplicationClientId(String realmName)
    • createComponentModel

      public static ComponentModel createComponentModel(String name, String parentId, String providerId, String providerType, String... config)
    • toLowerCaseSafe

      public static String toLowerCaseSafe(String str)
    • setupDefaultRole

      public 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
    • setupOfflineRole

      public static RoleModel setupOfflineRole(RealmModel realm)
    • setupDeleteAccount

      public static void setupDeleteAccount(ClientModel accountClient)
    • 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

      public static boolean escapeSlashesInGroupPath(KeycloakSession session)
      Helper to get from the session if group path slashes should be escaped or not.
      Parameters:
      session - The session
      Returns:
      true or false
    • findGroupByPath

      public static GroupModel findGroupByPath(KeycloakSession session, RealmModel realm, String path)
      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 session
      realm - The realm
      path - Path that will be searched among groups
      Returns:
      GroupModel corresponding to the given path or null if no group was found
    • findGroupByPath

      public static GroupModel findGroupByPath(KeycloakSession session, RealmModel realm, String[] path)
      Finds group by path. Variant when you have the path already separated by group names.
      Parameters:
      session - Keycloak session
      realm - The realm
      path - Path The path hierarchy of groups
      Returns:
      GroupModel corresponding to the given path or null if no group was found
    • splitPath

      public static String[] splitPath(String path, boolean escapedSlashes)
      Splits a group path than can be escaped for slashes.
      Parameters:
      path - The group path
      escapedSlashes - true if slashes are escaped in the path
      Returns:
    • buildGroupPath

      public static String buildGroupPath(boolean escapeSlashes, String... names)
    • buildGroupPath

      public static String buildGroupPath(GroupModel group)
    • buildGroupPath

      public static String buildGroupPath(GroupModel group, GroupModel otherParentGroup)
    • normalizeGroupPath

      public static String normalizeGroupPath(String groupPath)
    • getClientScopeMappingsStream

      public static Stream<RoleModel> getClientScopeMappingsStream(ClientModel client, ScopeContainerModel container)
    • getRoleFromString

      public static RoleModel getRoleFromString(RealmModel realm, String roleName)
    • parseRole

      public static String[] parseRole(String role)
    • buildRoleQualifier

      public static String buildRoleQualifier(String clientId, String roleName)
    • 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 session
      realm - The realm
      authFlow - flow to delete
      flowUnavailableHandler - Will be executed when flow, sub-flow or executor is null
      builtinFlowHandler - 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 session
      realm - The realm
      authExecutor - The authentication executor to remove
      flowUnavailableHandler - Handler that will be executed when flow, sub-flow or executor is null
      builtinFlowHandler - Handler that will be executed when flow is built-in flow
    • getClientScopeByName

      public static ClientScopeModel getClientScopeByName(RealmModel realm, String clientScopeName)
    • 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

      public static String convertClientScopeName(String previousName)
      Replace spaces in the name with underscore, so that scope name can be used as value of scope parameter
    • setupAuthorizationServices

      public static void setupAuthorizationServices(RealmModel realm)
    • suspendJtaTransaction

      public static void suspendJtaTransaction(KeycloakSessionFactory factory, Runnable runnable)
    • 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
    • isAdminPermissionsEnabled

      public static boolean isAdminPermissionsEnabled(RealmModel realm)