Service Provider Interface (SPI) contracts and abstractions for the Keycloak identity and access management server enabling extensibility through custom providers
—
The session management system in Keycloak SPI provides centralized access to all providers and services through the KeycloakSession interface. It also manages transactions, context information, and provider lifecycle.
The main session interface providing access to providers and transaction management.
public interface KeycloakSession extends AutoCloseable {
/**
* Gets the current request context information.
*
* @return the context
*/
KeycloakContext getContext();
/**
* Gets the transaction manager for this session.
*
* @return the transaction manager
*/
KeycloakTransactionManager getTransactionManager();
/**
* Gets a provider instance for the specified provider class.
* Uses the default provider implementation.
*
* @param clazz the provider class
* @return provider instance
*/
<T extends Provider> T getProvider(Class<T> clazz);
/**
* Gets a provider instance for the specified provider class and ID.
*
* @param clazz the provider class
* @param id the provider ID
* @return provider instance
*/
<T extends Provider> T getProvider(Class<T> clazz, String id);
/**
* Gets all provider instances for the specified provider class.
*
* @param clazz the provider class
* @return set of provider instances
*/
<T extends Provider> Set<T> getAllProviders(Class<T> clazz);
/**
* Gets the realm provider for realm operations.
*
* @return realm provider
*/
RealmProvider realms();
/**
* Gets the user provider for user operations.
*
* @return user provider
*/
UserProvider users();
/**
* Gets the client provider for client operations.
*
* @return client provider
*/
ClientProvider clients();
/**
* Gets the client scope provider for client scope operations.
*
* @return client scope provider
*/
ClientScopeProvider clientScopes();
/**
* Gets the group provider for group operations.
*
* @return group provider
*/
GroupProvider groups();
/**
* Gets the role provider for role operations.
*
* @return role provider
*/
RoleProvider roles();
/**
* Gets the user session provider for session operations.
*
* @return user session provider
*/
UserSessionProvider sessions();
/**
* Gets the authentication session provider.
*
* @return authentication session provider
*/
AuthenticationSessionProvider authenticationSessions();
/**
* Gets the user login failure provider.
*
* @return user login failure provider
*/
UserLoginFailureProvider loginFailures();
/**
* Gets the single use object provider.
*
* @return single use object provider
*/
SingleUseObjectProvider singleUseObjects();
/**
* Gets a named attribute from the session.
*
* @param attribute the attribute name
* @return attribute value
*/
Object getAttribute(String attribute);
/**
* Sets a named attribute in the session.
*
* @param name the attribute name
* @param value the attribute value
* @return previous value
*/
Object setAttribute(String name, Object value);
/**
* Removes a named attribute from the session.
*
* @param name the attribute name
* @return removed value
*/
Object removeAttribute(String name);
/**
* Gets the key manager for cryptographic operations.
*
* @return key manager
*/
KeyManager keys();
/**
* Gets the theme manager for theme operations.
*
* @return theme manager
*/
ThemeManager theme();
/**
* Gets the token manager for token operations.
*
* @return token manager
*/
TokenManager tokens();
/**
* Gets the vault transcriber for secret resolution.
*
* @return vault transcriber
*/
VaultTranscriber vault();
/**
* Gets the client policy manager.
*
* @return client policy manager
*/
ClientPolicyManager clientPolicy();
/**
* Invalidates cached objects of the specified type.
*
* @param type the object type to invalidate
* @param params invalidation parameters
*/
void invalidate(InvalidableObjectType type, Object... params);
}Factory for creating KeycloakSession instances.
public interface KeycloakSessionFactory extends AutoCloseable {
/**
* Creates a new Keycloak session.
*
* @return new session instance
*/
KeycloakSession create();
/**
* Creates a new Keycloak session for the specified realm.
*
* @param realmModel the realm
* @return new session instance
*/
KeycloakSession create(RealmModel realmModel);
/**
* Publishes an event to all event listeners.
*
* @param event the event to publish
*/
void publish(ProviderEvent event);
/**
* Registers an event listener.
*
* @param listener the event listener
*/
void register(ProviderEventListener listener);
/**
* Unregisters an event listener.
*
* @param listener the event listener
*/
void unregister(ProviderEventListener listener);
/**
* Gets the provider event manager.
*
* @return event manager
*/
ProviderEventManager getProviderEventManager();
}Provides access to request context information.
public interface KeycloakContext {
/**
* Gets the auth server URL.
*
* @return auth server URL
*/
URI getAuthServerUrl();
/**
* Gets the context path.
*
* @return context path
*/
String getContextPath();
/**
* Gets the URI information for the current request.
*
* @return URI info
*/
UriInfo getUri();
/**
* Gets the HTTP headers for the current request.
*
* @return HTTP headers
*/
HttpHeaders getRequestHeaders();
/**
* Gets the current realm.
*
* @return current realm or null
*/
RealmModel getRealm();
/**
* Sets the current realm.
*
* @param realm the realm to set
*/
void setRealm(RealmModel realm);
/**
* Gets the current client.
*
* @return current client or null
*/
ClientModel getClient();
/**
* Sets the current client.
*
* @param client the client to set
*/
void setClient(ClientModel client);
/**
* Gets the connection information.
*
* @return connection info
*/
ClientConnection getConnection();
/**
* Gets the Keycloak URI information.
*
* @return Keycloak URI info
*/
KeycloakUriInfo getUriInfo();
/**
* Gets the HTTP request.
*
* @return HTTP request
*/
HttpRequest getHttpRequest();
/**
* Gets the HTTP response.
*
* @return HTTP response
*/
HttpResponse getHttpResponse();
}Base interface for transactions.
public interface KeycloakTransaction {
/**
* Begins the transaction.
*/
void begin();
/**
* Commits the transaction.
*/
void commit();
/**
* Rolls back the transaction.
*/
void rollback();
/**
* Sets rollback only flag.
*/
void setRollbackOnly();
/**
* Checks if transaction is marked for rollback only.
*
* @return true if rollback only
*/
boolean getRollbackOnly();
/**
* Checks if transaction is active.
*
* @return true if active
*/
boolean isActive();
}Manages transactions for the session.
public interface KeycloakTransactionManager extends KeycloakTransaction {
/**
* Enlists a transaction participant.
*
* @param transaction the transaction to enlist
*/
void enlist(KeycloakTransaction transaction);
/**
* Enlists a transaction after completion callback.
*
* @param afterCompletion the callback
*/
void enlistAfterCompletion(KeycloakTransaction afterCompletion);
/**
* Enlists a transaction before completion callback.
*
* @param beforeCompletion the callback
*/
void enlistBeforeCompletion(KeycloakTransaction beforeCompletion);
/**
* Enlists a transaction prepared callback.
*
* @param prepared the callback
*/
void enlistPrepare(KeycloakTransaction prepared);
}Abstract base class for transaction implementations.
public abstract class AbstractKeycloakTransaction implements KeycloakTransaction {
private boolean started = false;
private boolean rollbackOnly = false;
@Override
public void begin() {
started = true;
}
@Override
public void commit() {
if (getRollbackOnly()) {
rollback();
return;
}
if (started) {
commitImpl();
}
}
@Override
public void rollback() {
if (started) {
rollbackImpl();
}
}
@Override
public void setRollbackOnly() {
rollbackOnly = true;
}
@Override
public boolean getRollbackOnly() {
return rollbackOnly;
}
@Override
public boolean isActive() {
return started;
}
/**
* Implement actual commit logic.
*/
protected abstract void commitImpl();
/**
* Implement actual rollback logic.
*/
protected abstract void rollbackImpl();
}Interface for tasks that need a Keycloak session.
public interface KeycloakSessionTask {
/**
* Runs the task with the provided session.
*
* @param session the Keycloak session
*/
void run(KeycloakSession session);
}Interface for tasks that return a result.
public interface KeycloakSessionTaskWithResult<V> {
/**
* Runs the task with the provided session and returns a result.
*
* @param session the Keycloak session
* @return task result
*/
V run(KeycloakSession session);
}// Create and use a session
try (KeycloakSession session = sessionFactory.create()) {
// Get providers
RealmProvider realms = session.realms();
UserProvider users = session.users();
// Get specific realm
RealmModel realm = realms.getRealmByName("myrealm");
session.getContext().setRealm(realm);
// Work with users
UserModel user = users.getUserByUsername(realm, "john");
if (user != null) {
user.setEmail("john@example.com");
}
// Transaction is automatically committed when session closes
}try (KeycloakSession session = sessionFactory.create()) {
KeycloakTransactionManager transaction = session.getTransactionManager();
// Begin transaction explicitly
transaction.begin();
try {
// Perform operations
RealmModel realm = session.realms().getRealmByName("myrealm");
UserModel user = session.users().addUser(realm, "newuser");
user.setEmail("newuser@example.com");
// Custom transaction participant
transaction.enlist(new KeycloakTransaction() {
@Override
public void begin() {}
@Override
public void commit() {
// Custom commit logic (e.g., send email)
sendWelcomeEmail(user);
}
@Override
public void rollback() {
// Custom rollback logic
}
@Override
public void setRollbackOnly() {}
@Override
public boolean getRollbackOnly() { return false; }
@Override
public boolean isActive() { return true; }
});
// Commit transaction
transaction.commit();
} catch (Exception e) {
transaction.rollback();
throw e;
}
}// Execute a task with automatic session management
sessionFactory.runInTransaction(session -> {
RealmModel realm = session.realms().getRealmByName("myrealm");
UserModel user = session.users().getUserByUsername(realm, "john");
if (user != null) {
user.setEnabled(false);
}
});
// Execute a task that returns a result
String result = sessionFactory.runInTransaction(session -> {
RealmModel realm = session.realms().getRealmByName("myrealm");
return realm.getDisplayName();
});try (KeycloakSession session = sessionFactory.create()) {
// Get default provider
UserStorageProvider userStorage = session.getProvider(UserStorageProvider.class);
// Get specific provider implementation
UserStorageProvider ldapProvider = session.getProvider(UserStorageProvider.class, "ldap");
// Get all provider implementations
Set<UserStorageProvider> allProviders = session.getAllProviders(UserStorageProvider.class);
// Access built-in providers
RealmProvider realms = session.realms();
UserProvider users = session.users();
ClientProvider clients = session.clients();
}try (KeycloakSession session = sessionFactory.create()) {
KeycloakContext context = session.getContext();
// Get request information
UriInfo uriInfo = context.getUri();
HttpHeaders headers = context.getRequestHeaders();
String userAgent = headers.getHeaderString("User-Agent");
// Get/set current realm and client
RealmModel realm = context.getRealm();
ClientModel client = context.getClient();
// Access connection info
ClientConnection connection = context.getConnection();
String remoteAddr = connection.getRemoteAddr();
String remoteHost = connection.getRemoteHost();
}try (KeycloakSession session = sessionFactory.create()) {
// Store data in session
session.setAttribute("myKey", "myValue");
// Retrieve data from session
String value = (String) session.getAttribute("myKey");
// Remove data from session
Object removed = session.removeAttribute("myKey");
}Install with Tessl CLI
npx tessl i tessl/maven-org-keycloak--keycloak-server-spi