Core Keycloak library providing fundamental authentication and authorization functionality
—
Essential utility functions for token processing, JSON serialization, basic authentication, and common operations. These utilities provide foundational support for Keycloak core functionality.
Comprehensive token processing and manipulation utilities for OAuth2/OIDC operations.
/**
* Token processing and manipulation utilities
*/
public class TokenUtil {
// Token type constants
/** Bearer token type constant */
public static final String TOKEN_TYPE_BEARER = "Bearer";
/** DPoP token type constant */
public static final String TOKEN_TYPE_DPOP = "DPoP";
/** ID token type constant */
public static final String TOKEN_TYPE_ID = "ID";
/** Refresh token type constant */
public static final String TOKEN_TYPE_REFRESH = "Refresh";
/**
* Attach OIDC scope parameter to query parameters
* @param queryParams Query parameters map
* @param formParams Form parameters map
*/
public static void attachOIDCScope(MultivaluedMap<String, String> queryParams,
MultivaluedMap<String, String> formParams);
/**
* Check if request contains OIDC scope
* @param scope Space-separated scope string
* @return true if OIDC scope is present
*/
public static boolean isOIDCRequest(String scope);
/**
* Check if offline token is requested in scope
* @param scope Space-separated scope string
* @return true if offline_access scope is present
*/
public static boolean isOfflineTokenRequested(String scope);
/**
* Check if specific scope is present in scope string
* @param scopes Space-separated scope string
* @param targetScope Scope to check for
* @return true if target scope is present
*/
public static boolean hasScope(String scopes, String targetScope);
/**
* Parse refresh token from token string
* @param refreshToken JWT refresh token string
* @return Parsed RefreshToken object
* @throws TokenVerificationException if parsing fails
*/
public static RefreshToken getRefreshToken(String refreshToken) throws TokenVerificationException;
/**
* Check if refresh token is an offline token
* @param refreshToken Parsed refresh token
* @return true if offline token
*/
public static boolean isOfflineToken(RefreshToken refreshToken);
/**
* Get token type from access token
* @param accessToken Access token instance
* @return Token type string
*/
public static String getTokenType(AccessToken accessToken);
/**
* Check if token has specific audience
* @param token JWT token
* @param audience Audience to check
* @return true if audience is present
*/
public static boolean hasAudience(JsonWebToken token, String audience);
/**
* Get token category from token instance
* @param token Token instance
* @return TokenCategory enum value
*/
public static TokenCategory getTokenCategory(Object token);
// JWE (JSON Web Encryption) utility methods
/**
* Encode object as JWE using direct encryption with shared key
* @param input Object to encrypt
* @param encryptionAlg Content encryption algorithm (e.g., "A256GCM")
* @param contentEncAlg Content encryption algorithm identifier
* @param encryptionKey Symmetric encryption key
* @return JWE token string
* @throws JWEException if encryption fails
*/
public static String jweDirectEncode(Object input, String encryptionAlg,
String contentEncAlg, SecretKey encryptionKey)
throws JWEException;
/**
* Verify and decode JWE token using direct decryption with shared key
* @param jweStr JWE token string
* @param encryptionKey Symmetric encryption key
* @return Decrypted object
* @throws JWEException if decryption fails
*/
public static <T> T jweDirectVerifyAndDecode(String jweStr, SecretKey encryptionKey)
throws JWEException;
/**
* Encode object as JWE using key encryption (RSA/ECDH)
* @param input Object to encrypt
* @param keyAlg Key management algorithm (e.g., "RSA-OAEP")
* @param encryptionAlg Content encryption algorithm (e.g., "A256GCM")
* @param contentEncAlg Content encryption algorithm identifier
* @param encryptionKey Public key for key encryption
* @return JWE token string
* @throws JWEException if encryption fails
*/
public static String jweKeyEncryptionEncode(Object input, String keyAlg,
String encryptionAlg, String contentEncAlg,
PublicKey encryptionKey)
throws JWEException;
/**
* Verify and decode JWE token using key decryption
* @param jweStr JWE token string
* @param decryptionKey Private key for key decryption
* @return Decrypted object
* @throws JWEException if decryption fails
*/
public static <T> T jweKeyEncryptionVerifyAndDecode(String jweStr, PrivateKey decryptionKey)
throws JWEException;
/**
* Create JWE encrypted with password-based key derivation
* @param input Object to encrypt
* @param password Password for key derivation
* @param salt Salt for key derivation
* @param iterations PBKDF2 iterations
* @return JWE token string
* @throws JWEException if encryption fails
*/
public static String jwePasswordEncode(Object input, String password, byte[] salt, int iterations)
throws JWEException;
/**
* Decrypt password-based JWE token
* @param jweStr JWE token string
* @param password Password for key derivation
* @return Decrypted object
* @throws JWEException if decryption fails
*/
public static <T> T jwePasswordVerifyAndDecode(String jweStr, String password)
throws JWEException;
}JSON serialization and deserialization utilities using Jackson ObjectMapper.
/**
* JSON serialization utilities using Jackson
*/
public class JsonSerialization {
/**
* Serialize object to JSON string
* @param obj Object to serialize
* @return JSON string representation
* @throws IOException if serialization fails
*/
public static String writeValueAsString(Object obj) throws IOException;
/**
* Serialize object to JSON byte array
* @param obj Object to serialize
* @return JSON byte array
* @throws IOException if serialization fails
*/
public static byte[] writeValueAsBytes(Object obj) throws IOException;
/**
* Write object to output stream as JSON
* @param out Output stream
* @param obj Object to serialize
* @throws IOException if serialization fails
*/
public static void writeValue(OutputStream out, Object obj) throws IOException;
/**
* Deserialize JSON string to object
* @param json JSON string
* @param type Target class type
* @return Deserialized object
* @throws IOException if deserialization fails
*/
public static <T> T readValue(String json, Class<T> type) throws IOException;
/**
* Deserialize JSON byte array to object
* @param json JSON byte array
* @param type Target class type
* @return Deserialized object
* @throws IOException if deserialization fails
*/
public static <T> T readValue(byte[] json, Class<T> type) throws IOException;
/**
* Deserialize JSON from input stream to object
* @param json JSON input stream
* @param type Target class type
* @return Deserialized object
* @throws IOException if deserialization fails
*/
public static <T> T readValue(InputStream json, Class<T> type) throws IOException;
/**
* Deserialize JSON to object with TypeReference for generic types
* @param json JSON string
* @param typeRef TypeReference for generic types
* @return Deserialized object
* @throws IOException if deserialization fails
*/
public static <T> T readValue(String json, TypeReference<T> typeRef) throws IOException;
/**
* Get the Jackson ObjectMapper instance
* @return Configured ObjectMapper
*/
public static ObjectMapper getMapper();
/**
* Configure ObjectMapper with custom settings
* @param mapper ObjectMapper to configure
*/
public static void configureMapper(ObjectMapper mapper);
/**
* Create a copy of an object through JSON serialization/deserialization
* @param obj Object to copy
* @param type Target class type
* @return Deep copy of the object
* @throws IOException if copy operation fails
*/
public static <T> T deepCopy(Object obj, Class<T> type) throws IOException;
/**
* Check if string is valid JSON
* @param json String to validate
* @return true if valid JSON
*/
public static boolean isValidJson(String json);
/**
* Pretty print JSON string
* @param json JSON string to format
* @return Formatted JSON string
* @throws IOException if formatting fails
*/
public static String prettyPrint(String json) throws IOException;
/**
* Convert object to JSON node for manipulation
* @param obj Object to convert
* @return JsonNode representation
*/
public static JsonNode toJsonNode(Object obj);
/**
* Convert JSON node to object
* @param node JsonNode to convert
* @param type Target class type
* @return Converted object
* @throws IOException if conversion fails
*/
public static <T> T fromJsonNode(JsonNode node, Class<T> type) throws IOException;
}HTTP Basic authentication utilities for client authentication.
/**
* HTTP Basic authentication utilities
*/
public class BasicAuthHelper {
/**
* Create HTTP Basic authentication header value
* @param username Username
* @param password Password
* @return Basic authentication header value (e.g., "Basic dXNlcjpwYXNz")
*/
public static String createHeader(String username, String password);
/**
* Parse HTTP Basic authentication header
* @param header Authorization header value
* @return Array containing username and password, or null if invalid
*/
public static String[] parseHeader(String header);
/**
* Extract username and password from Authorization header
* @param authHeader Full Authorization header value
* @return Array containing username and password, or null if invalid/not Basic
*/
public static String[] extractUsernamePassword(String authHeader);
/**
* Encode credentials for Basic authentication
* @param username Username
* @param password Password
* @return Base64 encoded credentials
*/
public static String encodeCredentials(String username, String password);
/**
* Decode Basic authentication credentials
* @param encodedCredentials Base64 encoded credentials
* @return Array containing username and password
* @throws IllegalArgumentException if credentials are invalid
*/
public static String[] decodeCredentials(String encodedCredentials);
/**
* Check if Authorization header is Basic authentication
* @param authHeader Authorization header value
* @return true if Basic authentication
*/
public static boolean isBasicAuth(String authHeader);
/**
* Create complete Authorization header for Basic authentication
* @param username Username
* @param password Password
* @return Complete Authorization header (e.g., "Authorization: Basic dXNlcjpwYXNz")
*/
public static String createAuthorizationHeader(String username, String password);
}JSON Web Key Set utilities for key management operations.
/**
* JSON Web Key Set utilities
*/
public class JWKSUtils {
/**
* Fetch JWK Set from URL
* @param jwksUrl JWK Set endpoint URL
* @return JSONWebKeySet instance
* @throws IOException if fetch operation fails
*/
public static JSONWebKeySet fetchJWKS(String jwksUrl) throws IOException;
/**
* Fetch JWK Set from URL with timeout
* @param jwksUrl JWK Set endpoint URL
* @param timeoutMs Timeout in milliseconds
* @return JSONWebKeySet instance
* @throws IOException if fetch operation fails
*/
public static JSONWebKeySet fetchJWKS(String jwksUrl, int timeoutMs) throws IOException;
/**
* Parse JWK Set from JSON string
* @param jwksJson JWK Set JSON string
* @return JSONWebKeySet instance
* @throws IOException if parsing fails
*/
public static JSONWebKeySet parseJWKS(String jwksJson) throws IOException;
/**
* Convert JWK Set to JSON string
* @param jwks JWK Set instance
* @return JSON string representation
* @throws IOException if serialization fails
*/
public static String toJsonString(JSONWebKeySet jwks) throws IOException;
/**
* Find key by key ID in JWK Set
* @param jwks JWK Set to search
* @param kid Key ID to find
* @return JWK instance or null if not found
*/
public static JWK findKeyById(JSONWebKeySet jwks, String kid);
/**
* Find keys by algorithm in JWK Set
* @param jwks JWK Set to search
* @param algorithm Algorithm identifier
* @return List of matching JWK instances
*/
public static List<JWK> findKeysByAlgorithm(JSONWebKeySet jwks, String algorithm);
/**
* Find keys by key use in JWK Set
* @param jwks JWK Set to search
* @param use Key use identifier (sig, enc)
* @return List of matching JWK instances
*/
public static List<JWK> findKeysByUse(JSONWebKeySet jwks, String use);
/**
* Validate JWK Set structure and keys
* @param jwks JWK Set to validate
* @return true if valid
*/
public static boolean validateJWKS(JSONWebKeySet jwks);
/**
* Create JWK Set from individual JWKs
* @param jwks Individual JWK instances
* @return JSONWebKeySet containing all keys
*/
public static JSONWebKeySet createJWKS(JWK... jwks);
/**
* Filter JWK Set by key type
* @param jwks Original JWK Set
* @param keyType Key type to filter by (RSA, EC, oct, OKP)
* @return Filtered JWK Set
*/
public static JSONWebKeySet filterByKeyType(JSONWebKeySet jwks, String keyType);
/**
* Merge multiple JWK Sets into one
* @param jwksSets JWK Sets to merge
* @return Merged JWK Set
*/
public static JSONWebKeySet mergeJWKS(JSONWebKeySet... jwksSets);
/**
* Cache JWK Set with TTL
* @param jwksUrl JWK Set URL
* @param jwks JWK Set to cache
* @param ttlSeconds Time to live in seconds
*/
public static void cacheJWKS(String jwksUrl, JSONWebKeySet jwks, int ttlSeconds);
/**
* Get cached JWK Set
* @param jwksUrl JWK Set URL
* @return Cached JWK Set or null if not cached or expired
*/
public static JSONWebKeySet getCachedJWKS(String jwksUrl);
}Cryptographic hash and encoding utilities for various operations.
/**
* Hash and encoding utilities
*/
public class HashUtils {
/**
* Compute SHA-256 hash of input data
* @param data Input data
* @return SHA-256 hash bytes
* @throws HashException if hash computation fails
*/
public static byte[] sha256(byte[] data) throws HashException;
/**
* Compute SHA-256 hash of string
* @param data Input string
* @return SHA-256 hash bytes
* @throws HashException if hash computation fails
*/
public static byte[] sha256(String data) throws HashException;
/**
* Compute SHA-384 hash of input data
* @param data Input data
* @return SHA-384 hash bytes
* @throws HashException if hash computation fails
*/
public static byte[] sha384(byte[] data) throws HashException;
/**
* Compute SHA-512 hash of input data
* @param data Input data
* @return SHA-512 hash bytes
* @throws HashException if hash computation fails
*/
public static byte[] sha512(byte[] data) throws HashException;
/**
* Encode bytes as Base64
* @param data Bytes to encode
* @return Base64 encoded string
*/
public static String encodeBase64(byte[] data);
/**
* Decode Base64 string to bytes
* @param base64 Base64 encoded string
* @return Decoded bytes
* @throws IllegalArgumentException if invalid Base64
*/
public static byte[] decodeBase64(String base64);
/**
* Encode bytes as Base64URL (URL-safe Base64)
* @param data Bytes to encode
* @return Base64URL encoded string
*/
public static String encodeBase64Url(byte[] data);
/**
* Decode Base64URL string to bytes
* @param base64Url Base64URL encoded string
* @return Decoded bytes
* @throws IllegalArgumentException if invalid Base64URL
*/
public static byte[] decodeBase64Url(String base64Url);
/**
* Generate secure random bytes
* @param length Number of bytes to generate
* @return Random bytes
*/
public static byte[] generateRandomBytes(int length);
/**
* Generate secure random string
* @param length String length
* @return Random string
*/
public static String generateRandomString(int length);
/**
* Compute HMAC-SHA256
* @param key HMAC key
* @param data Data to authenticate
* @return HMAC bytes
* @throws HashException if HMAC computation fails
*/
public static byte[] hmacSha256(byte[] key, byte[] data) throws HashException;
/**
* Verify HMAC-SHA256
* @param key HMAC key
* @param data Original data
* @param hmac HMAC to verify
* @return true if HMAC is valid
* @throws HashException if verification fails
*/
public static boolean verifyHmacSha256(byte[] key, byte[] data, byte[] hmac) throws HashException;
}import org.keycloak.util.*;
import org.keycloak.representations.*;
import org.keycloak.jose.jwk.*;
import javax.crypto.SecretKey;
import java.security.PublicKey;
import java.security.PrivateKey;
// Token utility usage
public class TokenUtilExample {
public void processTokenRequest(String scope, String tokenString) {
// Check for OIDC request
if (TokenUtil.isOIDCRequest(scope)) {
System.out.println("This is an OIDC request");
}
// Check for offline access
if (TokenUtil.isOfflineTokenRequested(scope)) {
System.out.println("Offline access requested");
}
// Check specific scope
if (TokenUtil.hasScope(scope, "profile")) {
System.out.println("Profile scope requested");
}
// Parse refresh token
try {
RefreshToken refreshToken = TokenUtil.getRefreshToken(tokenString);
if (TokenUtil.isOfflineToken(refreshToken)) {
System.out.println("This is an offline token");
}
} catch (TokenVerificationException e) {
System.err.println("Invalid refresh token: " + e.getMessage());
}
}
public void encryptSensitiveData(Object data, SecretKey key) {
try {
// Direct JWE encryption
String jwe = TokenUtil.jweDirectEncode(data, "A256GCM", "A256GCM", key);
System.out.println("Encrypted data: " + jwe);
// Decrypt data
Object decrypted = TokenUtil.jweDirectVerifyAndDecode(jwe, key);
System.out.println("Decrypted data: " + decrypted);
} catch (JWEException e) {
System.err.println("JWE operation failed: " + e.getMessage());
}
}
public void encryptWithPublicKey(Object data, PublicKey publicKey, PrivateKey privateKey) {
try {
// Key-encrypted JWE
String jwe = TokenUtil.jweKeyEncryptionEncode(data, "RSA-OAEP", "A256GCM", "A256GCM", publicKey);
System.out.println("Encrypted with public key: " + jwe);
// Decrypt with private key
Object decrypted = TokenUtil.jweKeyEncryptionVerifyAndDecode(jwe, privateKey);
System.out.println("Decrypted data: " + decrypted);
} catch (JWEException e) {
System.err.println("Key encryption failed: " + e.getMessage());
}
}
}
// JSON serialization usage
public class JsonSerializationExample {
public void serializeUserData() {
try {
// Create user object
UserRepresentation user = new UserRepresentation();
user.setUsername("john.doe");
user.setEmail("john@example.com");
user.setEnabled(true);
// Serialize to JSON
String json = JsonSerialization.writeValueAsString(user);
System.out.println("User JSON: " + json);
// Pretty print
String prettyJson = JsonSerialization.prettyPrint(json);
System.out.println("Pretty JSON:\n" + prettyJson);
// Deserialize back
UserRepresentation deserializedUser = JsonSerialization.readValue(json, UserRepresentation.class);
System.out.println("Deserialized username: " + deserializedUser.getUsername());
// Deep copy
UserRepresentation copy = JsonSerialization.deepCopy(user, UserRepresentation.class);
System.out.println("Copy email: " + copy.getEmail());
} catch (IOException e) {
System.err.println("JSON operation failed: " + e.getMessage());
}
}
public void handleGenericTypes() {
try {
// Working with generic types
Map<String, List<String>> attributes = new HashMap<>();
attributes.put("roles", Arrays.asList("admin", "user"));
attributes.put("groups", Arrays.asList("developers", "managers"));
String json = JsonSerialization.writeValueAsString(attributes);
// Deserialize with TypeReference
TypeReference<Map<String, List<String>>> typeRef = new TypeReference<Map<String, List<String>>>() {};
Map<String, List<String>> deserializedAttributes = JsonSerialization.readValue(json, typeRef);
System.out.println("Roles: " + deserializedAttributes.get("roles"));
} catch (IOException e) {
System.err.println("Generic type handling failed: " + e.getMessage());
}
}
}
// Basic authentication usage
public class BasicAuthExample {
public void handleBasicAuth(String username, String password) {
// Create Basic auth header
String authHeader = BasicAuthHelper.createHeader(username, password);
System.out.println("Authorization header: " + authHeader);
// Create complete header
String completeHeader = BasicAuthHelper.createAuthorizationHeader(username, password);
System.out.println("Complete header: " + completeHeader);
// Parse header
String[] credentials = BasicAuthHelper.parseHeader(authHeader);
if (credentials != null) {
System.out.println("Username: " + credentials[0]);
System.out.println("Password: " + credentials[1]);
}
}
public void processIncomingRequest(String authorizationHeader) {
if (BasicAuthHelper.isBasicAuth(authorizationHeader)) {
String[] credentials = BasicAuthHelper.extractUsernamePassword(authorizationHeader);
if (credentials != null) {
String username = credentials[0];
String password = credentials[1];
// Validate credentials
if (validateCredentials(username, password)) {
System.out.println("Authentication successful for: " + username);
} else {
System.out.println("Authentication failed");
}
}
}
}
private boolean validateCredentials(String username, String password) {
// Implementation would validate against user store
return true;
}
}
// JWK Set utilities usage
public class JWKSUtilsExample {
public void manageJWKS() {
try {
// Fetch JWK Set from URL
JSONWebKeySet jwks = JWKSUtils.fetchJWKS("https://auth.example.com/jwks", 5000);
System.out.println("Fetched " + jwks.getKeys().size() + " keys");
// Find key by ID
JWK signingKey = JWKSUtils.findKeyById(jwks, "rsa-key-1");
if (signingKey != null) {
System.out.println("Found signing key: " + signingKey.getKeyId());
}
// Find keys by algorithm
List<JWK> rsaKeys = JWKSUtils.findKeysByAlgorithm(jwks, "RS256");
System.out.println("Found " + rsaKeys.size() + " RSA keys");
// Filter by key type
JSONWebKeySet ecKeys = JWKSUtils.filterByKeyType(jwks, "EC");
System.out.println("EC keys: " + ecKeys.getKeys().size());
// Convert to JSON
String jwksJson = JWKSUtils.toJsonString(jwks);
System.out.println("JWK Set JSON length: " + jwksJson.length());
// Cache JWK Set
JWKSUtils.cacheJWKS("https://auth.example.com/jwks", jwks, 3600);
// Retrieve from cache
JSONWebKeySet cachedJWKS = JWKSUtils.getCachedJWKS("https://auth.example.com/jwks");
if (cachedJWKS != null) {
System.out.println("Retrieved from cache: " + cachedJWKS.getKeys().size() + " keys");
}
} catch (IOException e) {
System.err.println("JWK Set operation failed: " + e.getMessage());
}
}
}
// Hash utilities usage
public class HashUtilsExample {
public void performHashOperations() {
try {
String data = "Hello, Keycloak!";
// Compute hashes
byte[] sha256Hash = HashUtils.sha256(data);
byte[] sha384Hash = HashUtils.sha384(data.getBytes());
byte[] sha512Hash = HashUtils.sha512(data.getBytes());
// Encode as Base64
String sha256Base64 = HashUtils.encodeBase64(sha256Hash);
System.out.println("SHA-256 (Base64): " + sha256Base64);
// Encode as Base64URL
String sha256Base64Url = HashUtils.encodeBase64Url(sha256Hash);
System.out.println("SHA-256 (Base64URL): " + sha256Base64Url);
// Generate random data
byte[] randomBytes = HashUtils.generateRandomBytes(32);
String randomString = HashUtils.generateRandomString(16);
System.out.println("Random string: " + randomString);
// HMAC operations
byte[] key = HashUtils.generateRandomBytes(32);
byte[] hmac = HashUtils.hmacSha256(key, data.getBytes());
boolean valid = HashUtils.verifyHmacSha256(key, data.getBytes(), hmac);
System.out.println("HMAC valid: " + valid);
} catch (HashException e) {
System.err.println("Hash operation failed: " + e.getMessage());
}
}
}Install with Tessl CLI
npx tessl i tessl/maven-org-keycloak--keycloak-core