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 Summary
Fields Modifier and Type Field Description static String
AUTH_TYPE_CLIENT_SECRET
static String
AUTH_TYPE_CLIENT_SECRET_JWT
static String
GROUP_PATH_SEPARATOR
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static String
buildGroupPath(GroupModel group)
static String
buildGroupPath(GroupModel group, GroupModel otherParentGroup)
static String
buildRoleQualifier(String clientId, String roleName)
static Function<KeycloakSessionFactory,ComponentModel>
componentModelGetter(String realmId, String componentId)
static String
convertClientScopeName(String previousName)
Replace spaces in the name with underscore, so that scope name can be used as value of scope parameterstatic ComponentModel
createComponentModel(String name, String parentId, String providerId, String providerType, String... config)
static ClientModel
createManagementClient(RealmModel realm, String name)
static ClientModel
createPublicClient(RealmModel realm, String name)
static void
deepFindAuthenticationExecutions(RealmModel realm, AuthenticationFlowModel flow, List<AuthenticationExecutionModel> result)
Recursively find all AuthenticationExecutionModel from specified flow or all it's subflowsstatic ClientScopeModel
findClientScopeById(RealmModel realm, ClientModel client, String clientScopeId)
Lookup clientScope OR client by id.static GroupModel
findGroupByPath(RealmModel realm, String path)
static UserModel
findUserByNameOrEmail(KeycloakSession session, RealmModel realm, String username)
Try to find user by username or email for authenticationstatic String
generateCodeSecret()
static String
generateId()
static CertificateRepresentation
generateKeyPairCertificate(String subject)
static String
generateSecret(ClientModel client)
static X509Certificate
getCertificate(String cert)
static ClientScopeModel
getClientScopeByName(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 ComponentModel
getComponentModel(KeycloakSessionFactory factory, String realmId, String componentId)
static String
getDefaultClientAuthenticatorType()
static String
getIdentityProviderDisplayName(KeycloakSession session, IdentityProviderModel provider)
static String
getMasterRealmAdminApplicationClientId(String realmName)
static String
getPemFromCertificate(X509Certificate certificate)
static String
getPemFromKey(Key key)
static PrivateKey
getPrivateKey(String privateKeyPem)
static PublicKey
getPublicKey(String publicKeyPem)
static RoleModel
getRoleFromString(RealmModel realm, String roleName)
static Key
getSecretKey(String secret)
static int
getSecretLengthByAuthenticationType(String clientAuthenticatorType, String signingAlg)
static boolean
isExceptionRetriable(Throwable exception)
Checks if the specified exception is retriable or not.static boolean
isFlowUsed(RealmModel realm, AuthenticationFlowModel model)
Check to see if a flow is currently in usestatic boolean
isRealmProviderJpa(KeycloakSession session)
static boolean
isUsernameCaseSensitive(RealmModel realm)
Returnstrue
if given realm has attributeConstants.REALM_ATTR_USERNAME_CASE_SENSITIVE
set and its value istrue
.static String
normalizeGroupPath(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 String
resolveFirstAttribute(GroupModel group, String name)
static <V> V
runJobInRetriableTransaction(KeycloakSessionFactory factory, KeycloakSessionTaskWithResult<V> callable, int attemptsCount, int retryIntervalMillis)
Creates a newKeycloakSession
and runs the specified callable in a new transaction.static void
runJobInTransaction(KeycloakSessionFactory factory, KeycloakSessionTask task)
Wrap given runnable job into KeycloakTransaction.static <V> V
runJobInTransactionWithResult(KeycloakSessionFactory factory, KeycloakSessionTaskWithResult<V> callable)
Wrap a given callable job into a KeycloakTransaction.static void
runJobInTransactionWithTimeout(KeycloakSessionFactory factory, KeycloakSessionTask task, int timeoutInSeconds)
Wrap given runnable job into KeycloakTransaction.static boolean
searchFor(RoleModel role, RoleModel composite, Set<String> visited)
Deep search if given role is descendant of composite rolestatic void
setTransactionLimit(KeycloakSessionFactory factory, int timeoutInSeconds)
static void
setupAuthorizationServices(RealmModel realm)
static void
setupDefaultRole(RealmModel realm, String defaultRoleName)
Creates default role for particular realm with the given name.static void
setupDeleteAccount(ClientModel accountClient)
static RoleModel
setupOfflineRole(RealmModel realm)
static void
suspendJtaTransaction(KeycloakSessionFactory factory, Runnable runnable)
static String
toLowerCaseSafe(String str)
-
-
-
Field Detail
-
AUTH_TYPE_CLIENT_SECRET
public static final String AUTH_TYPE_CLIENT_SECRET
- See Also:
- Constant Field Values
-
AUTH_TYPE_CLIENT_SECRET_JWT
public static final String AUTH_TYPE_CLIENT_SECRET_JWT
- See Also:
- Constant Field Values
-
GROUP_PATH_SEPARATOR
public static final String GROUP_PATH_SEPARATOR
- See Also:
- Constant Field Values
-
-
Method Detail
-
generateId
public static String generateId()
-
getCertificate
public static X509Certificate getCertificate(String cert)
-
getPrivateKey
public static PrivateKey getPrivateKey(String privateKeyPem)
-
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 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
public static void runJobInTransaction(KeycloakSessionFactory factory, KeycloakSessionTask task)
Wrap given runnable job into KeycloakTransaction.
-
runJobInTransactionWithResult
public static <V> V runJobInTransactionWithResult(KeycloakSessionFactory factory, KeycloakSessionTaskWithResult<V> callable)
Wrap a given callable job into a KeycloakTransaction.
-
runJobInRetriableTransaction
public static <V> V runJobInRetriableTransaction(KeycloakSessionFactory factory, KeycloakSessionTaskWithResult<V> callable, int attemptsCount, int retryIntervalMillis)
Creates a newKeycloakSession
and 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 theKeycloakSessionTaskWithResult
that 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
public static boolean isExceptionRetriable(Throwable exception)
Checks if the specified exception is retriable or not. A retriable exception must be an instance ofSQLException
and 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:
true
if the exception is retriable;false
otherwise.
-
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)
-
setupDefaultRole
public static void setupDefaultRole(RealmModel realm, String defaultRoleName)
Creates default role for particular realm with the given name.- Parameters:
realm
- RealmdefaultRoleName
- 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
-
resolveFirstAttribute
public static String resolveFirstAttribute(GroupModel group, String name)
-
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(RealmModel realm, String path)
-
buildGroupPath
public static String buildGroupPath(GroupModel group)
-
buildGroupPath
public 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:
-
getClientScopeMappingsStream
public static Stream<RoleModel> getClientScopeMappingsStream(ClientModel client, ScopeContainerModel container)
-
getRoleFromString
public static RoleModel getRoleFromString(RealmModel realm, String roleName)
-
isFlowUsed
public static boolean isFlowUsed(RealmModel realm, AuthenticationFlowModel model)
Check to see if a flow is currently in use- Parameters:
realm
-model
-- Returns:
-
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)
-
isRealmProviderJpa
public static boolean isRealmProviderJpa(KeycloakSession session)
- 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
public static boolean isUsernameCaseSensitive(RealmModel realm)
Returnstrue
if given realm has attributeConstants.REALM_ATTR_USERNAME_CASE_SENSITIVE
set 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
- ifrealm
isnull
-
-