CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-keycloak--keycloak-adapter-core

Core functionality for Keycloak OIDC/OAuth2 client adapters enabling Java applications to integrate with Keycloak identity and access management services

Pending
Overview
Eval results
Files

utility-operations.mddocs/

Utility Operations

Utility functions for common adapter operations including principal name resolution, role extraction, HTTP requests, and credential management.

Capabilities

AdapterUtils

Core utility functions for adapter operations and principal management.

/**
 * Core utility functions for adapter operations and principal management
 */
public class AdapterUtils {
    /**
     * Generate a unique identifier
     * @return Randomly generated UUID string
     */
    public static String generateId();
    
    /**
     * Extract roles from security context based on deployment configuration
     * @param session Refreshable security context containing tokens
     * @return Set of role names, empty set if no roles found
     */
    public static Set<String> getRolesFromSecurityContext(RefreshableKeycloakSecurityContext session);
    
    /**
     * Get principal name from access token based on deployment attribute configuration
     * @param deployment Keycloak deployment configuration
     * @param token Access token containing user information
     * @return Principal name extracted from token, defaults to subject if configured attribute not found
     */
    public static String getPrincipalName(KeycloakDeployment deployment, AccessToken token);
    
    /**
     * Create a Keycloak principal from deployment and security context
     * @param deployment Keycloak deployment configuration
     * @param securityContext Security context containing token information
     * @return KeycloakPrincipal instance with resolved principal name
     */
    public static KeycloakPrincipal<RefreshableKeycloakSecurityContext> createPrincipal(
        KeycloakDeployment deployment, 
        RefreshableKeycloakSecurityContext securityContext
    );
    
    /**
     * Set client credentials in request headers and parameters
     * @param deployment Keycloak deployment configuration
     * @param headers Map to populate with credential headers
     * @param params Map to populate with credential parameters
     */
    public static void setClientCredentials(
        KeycloakDeployment deployment, 
        Map<String, String> headers, 
        Map<String, String> params
    );
}

Usage Examples:

// Generate unique identifier for state parameters
String state = AdapterUtils.generateId();

// Extract roles from authenticated user
RefreshableKeycloakSecurityContext securityContext = getSecurityContext();
Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext);

// Check for specific role
if (roles.contains("admin")) {
    // Allow admin operations
}

// Get principal name based on deployment configuration
AccessToken token = securityContext.getToken();
String principalName = AdapterUtils.getPrincipalName(deployment, token);

// Create principal for security frameworks
KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = 
    AdapterUtils.createPrincipal(deployment, securityContext);

// Set client credentials for HTTP requests
Map<String, String> headers = new HashMap<>();
Map<String, String> params = new HashMap<>();
AdapterUtils.setClientCredentials(deployment, headers, params);

// Apply credentials to HTTP request
for (Map.Entry<String, String> header : headers.entrySet()) {
    httpRequest.setHeader(header.getKey(), header.getValue());
}

HttpAdapterUtils

HTTP utility functions for JSON communication with Keycloak server.

/**
 * HTTP utility functions for JSON communication with Keycloak server
 */
public class HttpAdapterUtils {
    /**
     * Send HTTP request expecting JSON response
     * @param deployment Keycloak deployment configuration with HTTP client
     * @param httpRequest Configured HTTP request to execute
     * @param clazz Expected response type class
     * @param <T> Response type
     * @return Deserialized response object
     * @throws HttpClientAdapterException if HTTP request fails or response cannot be parsed
     */
    public static <T> T sendJsonHttpRequest(
        KeycloakDeployment deployment, 
        HttpRequestBase httpRequest, 
        Class<T> clazz
    ) throws HttpClientAdapterException;
}

Usage Examples:

// Create HTTP request for token introspection
HttpPost tokenRequest = new HttpPost(deployment.getTokenIntrospectionUrl());
tokenRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");

// Set form parameters
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("token", accessTokenString));
params.add(new BasicNameValuePair("token_type_hint", "access_token"));
tokenRequest.setEntity(new UrlEncodedFormEntity(params));

// Set client credentials
AdapterUtils.setClientCredentials(deployment, tokenRequest, new ArrayList<>());

try {
    // Execute request and parse JSON response
    TokenIntrospectionResponse response = HttpAdapterUtils.sendJsonHttpRequest(
        deployment, tokenRequest, TokenIntrospectionResponse.class
    );
    
    if (response.getActive()) {
        // Token is active
        String username = response.getUsername();
        Set<String> scopes = response.getScope();
    }
} catch (HttpClientAdapterException e) {
    // Handle request failure
    logger.error("Token introspection failed", e);
}

// Example with user info endpoint
HttpGet userInfoRequest = new HttpGet(deployment.getUserInfoUrl());
userInfoRequest.setHeader("Authorization", "Bearer " + accessTokenString);

try {
    UserInfo userInfo = HttpAdapterUtils.sendJsonHttpRequest(
        deployment, userInfoRequest, UserInfo.class
    );
    
    String email = userInfo.getEmail();
    String name = userInfo.getName();
} catch (HttpClientAdapterException e) {
    // Handle user info request failure
    logger.error("User info request failed", e);
}

PreAuthActionsHandler

Handler for pre-authentication actions like node registration, logout notifications, and admin requests.

/**
 * Handler for pre-authentication actions and administrative requests
 */
public class PreAuthActionsHandler {
    /**
     * Constructor for pre-authentication actions handler
     * @param userSessionManagement User session management implementation
     * @param deploymentContext Adapter deployment context
     * @param facade HTTP facade for request/response handling
     */
    public PreAuthActionsHandler(
        UserSessionManagement userSessionManagement,
        AdapterDeploymentContext deploymentContext,
        HttpFacade facade
    );
    
    /**
     * Handle request if it matches a pre-authentication action
     * @return true if request was handled, false if normal processing should continue
     */
    public boolean handleRequest();
}

Usage Examples:

// Handle pre-authentication actions before normal auth flow
PreAuthActionsHandler preAuthHandler = new PreAuthActionsHandler(
    userSessionManagement, deploymentContext, httpFacade
);

if (preAuthHandler.handleRequest()) {
    // Request was handled (e.g., admin logout, node registration)
    // Response has been sent, no further processing needed
    return;
}

// Continue with normal authentication flow
RequestAuthenticator authenticator = createAuthenticator(facade, deployment);
AuthOutcome outcome = authenticator.authenticate();

NodesRegistrationManagement

Management of cluster node registration with Keycloak server for distributed deployments.

/**
 * Management of cluster node registration with Keycloak server
 */
public class NodesRegistrationManagement {
    /**
     * Get node registration management instance
     * @return NodesRegistrationManagement singleton instance
     */
    public static NodesRegistrationManagement getInstance();
    
    /**
     * Try to register node with Keycloak server
     * @param deployment Keycloak deployment configuration
     */
    public void tryRegister(KeycloakDeployment deployment);
}

Usage Examples:

// Register application node with Keycloak for admin operations
NodesRegistrationManagement nodeManager = NodesRegistrationManagement.getInstance();

// Register during application startup
nodeManager.tryRegister(deployment);

// Registration typically happens automatically, but can be triggered manually
// This enables admin console operations like logout all users

SniSSLSocketFactory

SSL socket factory with Server Name Indication (SNI) support for secure HTTP connections.

/**
 * SSL socket factory with Server Name Indication (SNI) support
 */
public class SniSSLSocketFactory extends SSLSocketFactory {
    /**
     * Constructor with SSL context and hostname verifier
     * @param sslContext SSL context for secure connections
     * @param hostnameVerifier Hostname verification strategy
     */
    public SniSSLSocketFactory(SSLContext sslContext, X509HostnameVerifier hostnameVerifier);
    
    /**
     * Create SSL socket with SNI support
     * @param socket Base socket for SSL wrapping
     * @param host Target hostname for SNI
     * @param port Target port
     * @param autoClose Whether to auto-close underlying socket
     * @return SSL socket with SNI configuration
     * @throws IOException if socket creation fails
     */
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException;
}

Usage Examples:

// Create SSL context with custom trust store
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagers, new SecureRandom());

// Create SNI-enabled SSL socket factory
SniSSLSocketFactory sslSocketFactory = new SniSSLSocketFactory(
    sslContext, 
    SSLSocketFactory.STRICT_HOSTNAME_VERIFIER
);

// Configure HTTP client with SNI support
HttpClient httpClient = HttpClientBuilder.create()
    .setSSLSocketFactory(sslSocketFactory)
    .build();

// Use in deployment configuration
KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(config);
deployment.setClient(httpClient);

Install with Tessl CLI

npx tessl i tessl/maven-org-keycloak--keycloak-adapter-core

docs

authentication.md

core-adapters.md

http-operations.md

index.md

jaas-integration.md

key-rotation.md

policy-enforcement.md

token-storage.md

utility-operations.md

tile.json