Core Keycloak library providing fundamental authentication and authorization functionality
—
Core JWT token creation, validation, and processing with support for access tokens, ID tokens, refresh tokens, and specialized Keycloak token types.
Flexible JWT token validation system with configurable verification checks and support for various signature algorithms.
/**
* Generic JWT token verifier with pluggable verification predicates
* @param <T> Token type extending JsonWebToken
*/
public class TokenVerifier<T extends JsonWebToken> {
/**
* Create a token verifier instance for the specified token string and type
* @param tokenString Raw JWT token string
* @param clazz Token class type
* @return TokenVerifier instance
*/
public static <T extends JsonWebToken> TokenVerifier<T> create(String tokenString, Class<T> clazz);
/**
* Add default verification checks (expiration, not-before, issued-at)
* @return TokenVerifier instance for chaining
*/
public TokenVerifier<T> withDefaultChecks();
/**
* Set public key for signature verification
* @param publicKey Public key for RSA/ECDSA verification
* @return TokenVerifier instance for chaining
*/
public TokenVerifier<T> publicKey(PublicKey publicKey);
/**
* Set secret key for HMAC signature verification
* @param secretKey Secret key for HMAC verification
* @return TokenVerifier instance for chaining
*/
public TokenVerifier<T> secretKey(SecretKey secretKey);
/**
* Set expected audience claim values
* @param audience Expected audience values
* @return TokenVerifier instance for chaining
*/
public TokenVerifier<T> audience(String... audience);
/**
* Set expected issued-for claim value
* @param issuedFor Expected azp/client_id claim value
* @return TokenVerifier instance for chaining
*/
public TokenVerifier<T> issuedFor(String issuedFor);
/**
* Add custom verification predicates
* @param checks Custom verification predicates
* @return TokenVerifier instance for chaining
*/
@SafeVarargs
public final TokenVerifier<T> withChecks(Predicate<T>... checks);
/**
* Perform token verification
* @return TokenVerifier instance for chaining (call getToken() to get verified token)
* @throws VerificationException if verification fails
*/
public TokenVerifier<T> verify() throws VerificationException;
/**
* Get the verified token instance
* @return Token instance
* @throws VerificationException if token parsing fails
*/
public T getToken() throws VerificationException;
/**
* Get the token header without verification
* @return Token header
*/
public JWSHeader getHeader();
}Usage Examples:
import org.keycloak.TokenVerifier;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.IDToken;
import org.keycloak.common.VerificationException;
import org.keycloak.exceptions.TokenNotActiveException;
import org.keycloak.exceptions.TokenSignatureInvalidException;
import java.security.PublicKey;
// Basic access token verification
try {
AccessToken accessToken = TokenVerifier.create(tokenString, AccessToken.class)
.withDefaultChecks()
.publicKey(rsaPublicKey)
.audience("my-client-id")
.verify()
.getToken();
// Token is valid, extract information
String subject = accessToken.getSubject();
String scope = accessToken.getScope();
Set<String> roles = accessToken.getRealmAccess().getRoles();
} catch (VerificationException e) {
// Handle verification failure
System.err.println("Token verification failed: " + e.getMessage());
}
// ID token verification with custom checks
IDToken idToken = TokenVerifier.create(idTokenString, IDToken.class)
.withDefaultChecks()
.publicKey(publicKey)
.audience("web-client")
.withChecks(token -> {
// Custom check: ensure email is verified
return Boolean.TRUE.equals(token.getEmailVerified());
})
.verify()
.getToken();
// HMAC token verification
AccessToken hmacToken = TokenVerifier.create(tokenString, AccessToken.class)
.withDefaultChecks()
.secretKey(hmacSecretKey)
.verify()
.getToken();Built-in and custom verification predicates for advanced token validation scenarios.
/**
* Custom verification predicate interface
* @param <T> Token type
*/
public interface Predicate<T> {
/**
* Test the token against custom criteria
* @param token Token to test
* @return true if verification passes
* @throws TokenVerificationException if verification fails
*/
boolean test(T token) throws TokenVerificationException;
}
/**
* Built-in verification predicates
*/
public static class TokenVerifier {
/**
* Realm URL verification predicate
*/
public static class RealmUrlCheck implements Predicate<JsonWebToken> {
public RealmUrlCheck(String realmUrl);
public boolean test(JsonWebToken token) throws TokenVerificationException;
}
/**
* Token type verification predicate
*/
public static class TokenTypeCheck implements Predicate<JsonWebToken> {
public TokenTypeCheck(String expectedType);
public boolean test(JsonWebToken token) throws TokenVerificationException;
}
/**
* Audience verification predicate
*/
public static class AudienceCheck implements Predicate<JsonWebToken> {
public AudienceCheck(String... expectedAudience);
public boolean test(JsonWebToken token) throws TokenVerificationException;
}
/**
* Issued-for verification predicate
*/
public static class IssuedForCheck implements Predicate<JsonWebToken> {
public IssuedForCheck(String expectedIssuedFor);
public boolean test(JsonWebToken token) throws TokenVerificationException;
}
}Base token interface and category system for all JWT token types.
/**
* Base marker interface for all token types
*/
public interface Token {
/**
* Get the token category
* @return Token category enum value
*/
TokenCategory getCategory();
}
/**
* Token category enumeration for classifying different token types
*/
public enum TokenCategory {
/** Internal system tokens */
INTERNAL,
/** OAuth2 access tokens */
ACCESS,
/** OpenID Connect ID tokens */
ID,
/** Administrative tokens */
ADMIN,
/** UserInfo endpoint tokens */
USERINFO,
/** Logout tokens */
LOGOUT,
/** Authorization response tokens */
AUTHORIZATION_RESPONSE
}RSA key pair verification utility for validating public/private key relationships.
/**
* Utility for verifying RSA key pair relationships
*/
public class KeyPairVerifier {
/**
* Verify that a public and private key form a valid RSA key pair
* @param privateKey RSA private key
* @param publicKey RSA public key
* @return true if keys form a valid pair
*/
public static boolean verify(PrivateKey privateKey, PublicKey publicKey);
}Legacy RSA-specific token verification utility (deprecated in favor of TokenVerifier).
/**
* Legacy RSA token verifier utility
* @deprecated Use TokenVerifier with publicKey() method instead
*/
@Deprecated
public class RSATokenVerifier {
/**
* Verify RSA-signed token
* @param token Token string
* @param publicKey RSA public key
* @return Parsed access token
* @throws TokenVerificationException if verification fails
*/
public static AccessToken verifyToken(String token, PublicKey publicKey)
throws TokenVerificationException;
}Utility for generating unique token identifiers.
/**
* Token ID generation utility
*/
public class TokenIdGenerator {
/**
* Generate a unique token identifier
* @return Unique token ID string
*/
public static String generateId();
/**
* Generate a unique token identifier with custom prefix
* @param prefix Custom prefix for the token ID
* @return Unique token ID string with prefix
*/
public static String generateId(String prefix);
}/**
* Base exception for token verification failures
*/
public class TokenVerificationException extends Exception {
public TokenVerificationException(String message);
public TokenVerificationException(String message, Throwable cause);
public TokenVerificationException(JsonWebToken token, String message);
public TokenVerificationException(JsonWebToken token, String message, Throwable cause);
/**
* Get the token that failed verification (if available)
* @return Token instance or null
*/
public JsonWebToken getToken();
}
/**
* Exception thrown when token is not active (expired or not yet valid)
*/
public class TokenNotActiveException extends TokenVerificationException {
public TokenNotActiveException(JsonWebToken token, String message);
}
/**
* Exception thrown when token signature is invalid
*/
public class TokenSignatureInvalidException extends TokenVerificationException {
public TokenSignatureInvalidException(JsonWebToken token, String message);
}Usage Examples:
try {
AccessToken token = TokenVerifier.create(tokenString, AccessToken.class)
.withDefaultChecks()
.publicKey(publicKey)
.verify()
.getToken();
} catch (TokenNotActiveException e) {
// Token is expired or not yet valid
System.err.println("Token is not active: " + e.getMessage());
} catch (TokenSignatureInvalidException e) {
// Token signature verification failed
System.err.println("Invalid token signature: " + e.getMessage());
} catch (TokenVerificationException e) {
// Other verification failures
System.err.println("Token verification failed: " + e.getMessage());
}Install with Tessl CLI
npx tessl i tessl/maven-org-keycloak--keycloak-core