CtrlK
BlogDocsLog inGet started
Tessl Logo

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

Core Keycloak library providing fundamental authentication and authorization functionality

Pending
Overview
Eval results
Files

security-context.mddocs/

Security Context

Runtime security context management providing access to authentication state, token information, and authorization decisions. These components form the foundation for request-level security operations in Keycloak-secured applications.

Capabilities

Keycloak Security Context

Core security context containing authentication and authorization information for the current request.

/**
 * Security context containing authentication and authorization information
 */
public class KeycloakSecurityContext {
    /**
     * Get the access token
     * @return Parsed AccessToken instance
     */
    public AccessToken getToken();
    
    /**
     * Get the raw access token string
     * @return JWT access token string
     */
    public String getTokenString();
    
    /**
     * Get the ID token
     * @return Parsed IDToken instance or null if not available
     */
    public IDToken getIdToken();
    
    /**
     * Get the raw ID token string
     * @return JWT ID token string or null if not available
     */
    public String getIdTokenString();
    
    /**
     * Get the refresh token
     * @return Parsed RefreshToken instance or null if not available
     */
    public RefreshToken getRefreshToken();
    
    /**
     * Get the raw refresh token string
     * @return JWT refresh token string or null if not available
     */
    public String getRefreshTokenString();
    
    /**
     * Get the authorization context for permission checking
     * @return AuthorizationContext instance or null if not available
     */
    public AuthorizationContext getAuthorizationContext();
    
    /**
     * Get the realm name
     * @return Realm identifier
     */
    public String getRealm();
    
    /**
     * Check if the security context is active (tokens not expired)
     * @return true if context is active
     */
    public boolean isActive();
    
    /**
     * Get the token category
     * @return TokenCategory enum value
     */
    public TokenCategory getTokenCategory();
}

Authorization Context

Permission management and authorization decision support for UMA (User-Managed Access) permissions.

/**
 * Authorization context for permission checking and UMA support
 */
public class AuthorizationContext {
    /**
     * Check if user has permission for specific resource and scope
     * @param resource Resource identifier
     * @param scope Scope identifier
     * @return true if permission exists
     */
    public boolean hasPermission(String resource, String scope);
    
    /**
     * Check if user has permission for specific resource (any scope)
     * @param resource Resource identifier
     * @return true if any permission exists for the resource
     */
    public boolean hasResourcePermission(String resource);
    
    /**
     * Check if user has permission for specific scope (any resource)
     * @param scope Scope identifier
     * @return true if any permission exists for the scope
     */
    public boolean hasScopePermission(String scope);
    
    /**
     * Get all permissions for the current user
     * @return Collection of Permission objects
     */
    public Collection<Permission> getPermissions();
    
    /**
     * Get permissions for a specific resource
     * @param resource Resource identifier
     * @return Collection of permissions for the resource
     */
    public Collection<Permission> getPermissions(String resource);
    
    /**
     * Check if any permissions are granted
     * @return true if at least one permission is granted
     */
    public boolean isGranted();
    
    /**
     * Check if authorization is disabled
     * @return true if authorization checks are disabled
     */
    public boolean isDisabled();
    
    /**
     * Get the authorization token (if available)
     * @return Authorization token or null
     */
    public String getAuthorizationToken();
}

/**
 * Individual permission representation
 */
public class Permission {
    /**
     * Get the resource identifier
     * @return Resource identifier
     */
    public String getResourceId();
    
    /**
     * Get the resource name
     * @return Resource name
     */
    public String getResourceName();
    
    /**
     * Get the scopes for this permission
     * @return Set of scope names
     */
    public Set<String> getScopes();
    
    /**
     * Check if permission includes specific scope
     * @param scope Scope name to check
     * @return true if scope is included
     */
    public boolean hasScope(String scope);
    
    /**
     * Get additional claims for this permission
     * @return Map of additional claims
     */
    public Map<String, Object> getClaims();
    
    /**
     * Get specific claim value
     * @param name Claim name
     * @return Claim value or null
     */
    public Object getClaim(String name);
}

Keycloak Principal

Java Principal implementation for authenticated users in Keycloak-secured applications.

/**
 * Java Principal implementation for Keycloak authentication
 * @param <T> Security context type extending KeycloakSecurityContext
 */
public class KeycloakPrincipal<T extends KeycloakSecurityContext> implements Principal, Serializable {
    /**
     * Create principal with security context
     * @param name Principal name
     * @param securityContext Keycloak security context
     */
    public KeycloakPrincipal(String name, T securityContext);
    
    /**
     * Get the principal name (usually the subject from the token)
     * @return Principal name
     */
    public String getName();
    
    /**
     * Get the Keycloak security context
     * @return Security context instance
     */
    public T getKeycloakSecurityContext();
    
    /**
     * Check equality with another principal
     * @param obj Object to compare
     * @return true if principals are equal
     */
    public boolean equals(Object obj);
    
    /**
     * Get hash code for the principal
     * @return Hash code
     */
    public int hashCode();
    
    /**
     * Get string representation of the principal
     * @return String representation
     */
    public String toString();
}

Token Store Enumeration

Token storage mechanisms for different deployment scenarios.

/**
 * Token storage type enumeration for different deployment scenarios
 */
public enum TokenStore {
    /**
     * Store tokens in HTTP session (default for web applications)
     */
    SESSION,
    
    /**
     * Store tokens in HTTP cookies (for stateless applications)
     */
    COOKIE;
    
    /**
     * Get the token store name
     * @return Token store name in lowercase
     */
    public String getTokenStoreName();
}

OAuth Error Handling

OAuth-specific error exception for authentication and authorization failures.

/**
 * OAuth-specific error exception
 */
public class OAuthErrorException extends Exception {
    /**
     * Create OAuth error exception
     * @param error OAuth error code
     * @param description Error description
     */
    public OAuthErrorException(String error, String description);
    
    /**
     * Create OAuth error exception with cause
     * @param error OAuth error code
     * @param description Error description
     * @param cause Underlying cause
     */
    public OAuthErrorException(String error, String description, Throwable cause);
    
    /**
     * Get the OAuth error code
     * @return Error code (e.g., "invalid_token", "access_denied")
     */
    public String getError();
    
    /**
     * Get the error description
     * @return Human-readable error description
     */
    public String getDescription();
    
    /**
     * Get the error URI (if available)
     * @return Error URI or null
     */
    public String getErrorUri();
}

Abstract OAuth Client

Base implementation for OAuth clients with common functionality.

/**
 * Abstract base class for OAuth client implementations
 */
public abstract class AbstractOAuthClient {
    /**
     * Get the client ID
     * @return Client identifier
     */
    public String getClientId();
    
    /**
     * Set the client ID
     * @param clientId Client identifier
     */
    public void setClientId(String clientId);
    
    /**
     * Get the client secret
     * @return Client secret
     */
    public String getClientSecret();
    
    /**
     * Set the client secret
     * @param clientSecret Client secret
     */
    public void setClientSecret(String clientSecret);
    
    /**
     * Get the auth server URL
     * @return Authorization server URL
     */
    public String getAuthUrl();
    
    /**
     * Set the auth server URL
     * @param authUrl Authorization server URL
     */
    public void setAuthUrl(String authUrl);
    
    /**
     * Get the token endpoint URL
     * @return Token endpoint URL
     */
    public String getTokenUrl();
    
    /**
     * Set the token endpoint URL
     * @param tokenUrl Token endpoint URL
     */
    public void setTokenUrl(String tokenUrl);
    
    /**
     * Get the redirect URI
     * @return Redirect URI
     */
    public String getRedirectUri();
    
    /**
     * Set the redirect URI
     * @param redirectUri Redirect URI
     */
    public void setRedirectUri(String redirectUri);
    
    /**
     * Get the requested scope
     * @return Space-separated scope values
     */
    public String getScope();
    
    /**
     * Set the requested scope
     * @param scope Space-separated scope values
     */
    public void setScope(String scope);
    
    /**
     * Check if HTTPS is required
     * @return true if HTTPS required
     */
    public boolean isHttpsRequired();
    
    /**
     * Set HTTPS required flag
     * @param httpsRequired HTTPS required flag
     */
    public void setHttpsRequired(boolean httpsRequired);
    
    /**
     * Generate authorization URL
     * @param state State parameter for CSRF protection
     * @return Authorization URL
     */
    public abstract String generateAuthUrl(String state);
    
    /**
     * Exchange authorization code for tokens
     * @param code Authorization code
     * @return Access token response
     * @throws OAuthErrorException if token exchange fails
     */
    public abstract AccessTokenResponse exchangeCodeForToken(String code) throws OAuthErrorException;
    
    /**
     * Refresh access token using refresh token
     * @param refreshToken Refresh token
     * @return New access token response
     * @throws OAuthErrorException if token refresh fails
     */
    public abstract AccessTokenResponse refreshToken(String refreshToken) throws OAuthErrorException;
}

Usage Examples

import org.keycloak.*;
import org.keycloak.representations.*;
import javax.servlet.http.HttpServletRequest;

// Working with KeycloakSecurityContext
public class SecureController {
    
    public void handleSecureRequest(HttpServletRequest request) {
        // Get security context from request
        KeycloakSecurityContext securityContext = 
            (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
        
        if (securityContext != null && securityContext.isActive()) {
            // Access token information
            AccessToken token = securityContext.getToken();
            String subject = token.getSubject();
            String realm = securityContext.getRealm();
            
            // Check roles
            AccessToken.Access realmAccess = token.getRealmAccess();
            if (realmAccess != null && realmAccess.isUserInRole("admin")) {
                // Handle admin access
                handleAdminRequest(securityContext);
            }
            
            // Check client-specific roles
            AccessToken.Access clientAccess = token.getResourceAccess("my-app");
            if (clientAccess != null && clientAccess.isUserInRole("manager")) {
                // Handle manager access
                handleManagerRequest(securityContext);
            }
            
            // Work with ID token if available
            IDToken idToken = securityContext.getIdToken();
            if (idToken != null) {
                String email = idToken.getEmail();
                String name = idToken.getName();
                // Use profile information
                updateUserProfile(email, name);
            }
        }
    }
    
    private void handleAdminRequest(KeycloakSecurityContext context) {
        // Check authorization permissions
        AuthorizationContext authz = context.getAuthorizationContext();
        if (authz != null) {
            // Check specific resource permissions
            if (authz.hasPermission("user-management", "read")) {
                // Allow reading user data
            }
            
            if (authz.hasPermission("user-management", "write")) {
                // Allow modifying user data
            }
            
            // Get all permissions
            Collection<Permission> permissions = authz.getPermissions();
            for (Permission permission : permissions) {
                String resourceName = permission.getResourceName();
                Set<String> scopes = permission.getScopes();
                // Process permissions
            }
        }
    }
    
    private void handleManagerRequest(KeycloakSecurityContext context) {
        AccessToken token = context.getToken();
        
        // Check token expiration
        if (token.isExpired()) {
            // Handle token refresh or re-authentication
            handleTokenExpiration(context);
            return;
        }
        
        // Check specific permissions
        AuthorizationContext authz = context.getAuthorizationContext();
        if (authz != null && authz.hasResourcePermission("project-data")) {
            // Allow access to project data
            allowProjectAccess();
        }
    }
    
    private void handleTokenExpiration(KeycloakSecurityContext context) {
        // Check if refresh token is available
        RefreshToken refreshToken = context.getRefreshToken();
        if (refreshToken != null && !refreshToken.isExpired()) {
            // Initiate token refresh
            initiateTokenRefresh(context.getRefreshTokenString());
        } else {
            // Redirect to authentication
            redirectToLogin();
        }
    }
}

// Working with KeycloakPrincipal
public class PrincipalExample {
    
    public void handlePrincipal(Principal principal) {
        if (principal instanceof KeycloakPrincipal) {
            KeycloakPrincipal keycloakPrincipal = (KeycloakPrincipal) principal;
            KeycloakSecurityContext context = keycloakPrincipal.getKeycloakSecurityContext();
            
            // Get user information
            AccessToken token = context.getToken();
            String username = token.getPreferredUsername();
            String email = token.getEmail();
            
            // Log user activity
            logUserActivity(username, "Accessed secure resource");
        }
    }
}

// OAuth client implementation
public class MyOAuthClient extends AbstractOAuthClient {
    
    @Override
    public String generateAuthUrl(String state) {
        StringBuilder url = new StringBuilder(getAuthUrl());
        url.append("?response_type=code");
        url.append("&client_id=").append(getClientId());
        url.append("&redirect_uri=").append(getRedirectUri());
        url.append("&scope=").append(getScope());
        url.append("&state=").append(state);
        return url.toString();
    }
    
    @Override
    public AccessTokenResponse exchangeCodeForToken(String code) throws OAuthErrorException {
        // Implementation for token exchange
        // Make HTTP POST to token endpoint
        // Parse response and return AccessTokenResponse
        // Throw OAuthErrorException on error
        return null; // Implementation would return actual response
    }
    
    @Override
    public AccessTokenResponse refreshToken(String refreshToken) throws OAuthErrorException {
        // Implementation for token refresh
        // Make HTTP POST to token endpoint with refresh_token grant
        // Parse response and return AccessTokenResponse
        // Throw OAuthErrorException on error
        return null; // Implementation would return actual response
    }
}

// Error handling
public class ErrorHandlingExample {
    
    public void handleOAuthError() {
        try {
            // OAuth operation that might fail
            performOAuthOperation();
        } catch (OAuthErrorException e) {
            String errorCode = e.getError();
            String description = e.getDescription();
            
            switch (errorCode) {
                case "invalid_token":
                    // Handle invalid token
                    handleInvalidToken(description);
                    break;
                case "access_denied":
                    // Handle access denied
                    handleAccessDenied(description);
                    break;
                case "invalid_grant":
                    // Handle invalid grant
                    handleInvalidGrant(description);
                    break;
                default:
                    // Handle unknown error
                    handleUnknownError(errorCode, description);
            }
        }
    }
}

Install with Tessl CLI

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

docs

configuration-management.md

cryptographic-operations.md

identity-management.md

index.md

jose-implementation.md

security-context.md

token-management.md

token-representations.md

utility-functions.md

tile.json