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

token-representations.mddocs/

Token Representations

Comprehensive token representation classes for OAuth2/OpenID Connect tokens with Keycloak extensions for roles, permissions, and authorization. These classes provide type-safe access to JWT claims and specialized Keycloak features.

Capabilities

Base JWT Token

Foundation class for all JWT token types with standard claims support.

/**
 * Base JWT implementation with standard RFC 7519 claims
 */
public class JsonWebToken implements Token {
    /**
     * Check if token is expired
     * @return true if current time is past expiration
     */
    public boolean isExpired();
    
    /**
     * Check if token is active (not expired and not before time has passed)
     * @return true if token is currently valid for time-based checks
     */
    public boolean isActive();
    
    /**
     * Get the issuer claim (iss)
     * @return Issuer identifier
     */
    public String getIssuer();
    
    /**
     * Get the subject claim (sub)
     * @return Subject identifier
     */
    public String getSubject();
    
    /**
     * Get the audience claim (aud) as array
     * @return Array of audience values
     */
    public String[] getAudience();
    
    /**
     * Check if token has specific audience
     * @param audience Audience to check
     * @return true if audience is present
     */
    public boolean hasAudience(String audience);
    
    /**
     * Get the expiration time claim (exp)
     * @return Expiration timestamp
     */
    public Long getExpiration();
    
    /**
     * Get the not-before time claim (nbf)
     * @return Not-before timestamp
     */
    public Long getNotBefore();
    
    /**
     * Get the issued-at time claim (iat)
     * @return Issued-at timestamp
     */
    public Long getIssuedAt();
    
    /**
     * Get the JWT ID claim (jti)
     * @return JWT identifier
     */
    public String getId();
    
    /**
     * Get all other claims not covered by standard methods
     * @return Map of additional claims
     */
    public Map<String, Object> getOtherClaims();
    
    /**
     * Get the token category for classification
     * @return TokenCategory enum value
     */
    public TokenCategory getCategory();
}

Access Token

OAuth2 access token with Keycloak extensions for roles and permissions.

/**
 * OAuth2 access token with Keycloak role and permission extensions
 */
public class AccessToken extends JsonWebToken {
    /**
     * Get the scope claim
     * @return Space-separated scope values
     */
    public String getScope();
    
    /**
     * Get the session state identifier
     * @return Session state value
     */
    public String getSessionState();
    
    /**
     * Get allowed origins for CORS
     * @return Set of allowed origin URLs
     */
    public Set<String> getAllowedOrigins();
    
    /**
     * Get realm-level access information
     * @return Access object with realm roles
     */
    public Access getRealmAccess();
    
    /**
     * Get resource-level access information for all resources
     * @return Map of resource name to Access object
     */
    public Map<String, Access> getResourceAccess();
    
    /**
     * Get resource-level access information for specific resource
     * @param resource Resource name
     * @return Access object or null if not found
     */
    public Access getResourceAccess(String resource);
    
    /**
     * Get authorization information (UMA permissions)
     * @return Authorization object with permissions
     */
    public Authorization getAuthorization();
    
    /**
     * Get the trusted certificates
     * @return Set of trusted certificate identifiers
     */
    public Set<String> getTrustedCertificates();
    
    /**
     * Access control information for roles and permissions
     */
    public static class Access {
        /**
         * Get all roles
         * @return Set of role names
         */
        public Set<String> getRoles();
        
        /**
         * Check if user has specific role
         * @param role Role name to check
         * @return true if role is present
         */
        public boolean isUserInRole(String role);
        
        /**
         * Verify user has specific role (throws exception if not)
         * @param role Role name to verify
         * @throws AccessDeniedException if role not present
         */
        public void verify(String role) throws AccessDeniedException;
        
        /**
         * Add role to the access object
         * @param roleName Role name to add
         */
        public void addRole(String roleName);
    }
    
    /**
     * Authorization information for UMA permissions
     */
    public static class Authorization {
        /**
         * Get all permissions
         * @return List of Permission objects
         */
        public List<Permission> getPermissions();
        
        /**
         * Check if user has permission for resource and scope
         * @param resource Resource identifier
         * @param scope Scope identifier
         * @return true if permission exists
         */
        public boolean hasPermission(String resource, String scope);
        
        /**
         * Get permissions for specific resource
         * @param resource Resource identifier
         * @return List of permissions for the resource
         */
        public List<Permission> getPermissions(String resource);
    }
}

ID Token

OpenID Connect ID token with standard OIDC claims.

/**
 * OpenID Connect ID token with standard profile claims
 */
public class IDToken extends JsonWebToken {
    /**
     * Get the full name claim (name)
     * @return Full name
     */
    public String getName();
    
    /**
     * Get the given name claim (given_name)
     * @return Given/first name
     */
    public String getGivenName();
    
    /**
     * Get the family name claim (family_name)
     * @return Family/last name
     */
    public String getFamilyName();
    
    /**
     * Get the middle name claim (middle_name)
     * @return Middle name
     */
    public String getMiddleName();
    
    /**
     * Get the nickname claim (nickname)
     * @return Nickname
     */
    public String getNickname();
    
    /**
     * Get the preferred username claim (preferred_username)
     * @return Preferred username
     */
    public String getPreferredUsername();
    
    /**
     * Get the profile URL claim (profile)
     * @return Profile page URL
     */
    public String getProfile();
    
    /**
     * Get the picture URL claim (picture)
     * @return Profile picture URL
     */
    public String getPicture();
    
    /**
     * Get the website URL claim (website)
     * @return Website URL
     */
    public String getWebsite();
    
    /**
     * Get the email address claim (email)
     * @return Email address
     */
    public String getEmail();
    
    /**
     * Get the email verification status claim (email_verified)
     * @return Email verification status
     */
    public Boolean getEmailVerified();
    
    /**
     * Get the gender claim (gender)
     * @return Gender value
     */
    public String getGender();
    
    /**
     * Get the birthdate claim (birthdate)
     * @return Birthdate string (YYYY-MM-DD format)
     */
    public String getBirthdate();
    
    /**
     * Get the timezone claim (zoneinfo)
     * @return Timezone identifier
     */
    public String getZoneinfo();
    
    /**
     * Get the locale claim (locale)
     * @return Locale identifier
     */
    public String getLocale();
    
    /**
     * Get the phone number claim (phone_number)
     * @return Phone number
     */
    public String getPhoneNumber();
    
    /**
     * Get the phone verification status claim (phone_number_verified)
     * @return Phone verification status
     */
    public Boolean getPhoneNumberVerified();
    
    /**
     * Get the address claim (address)
     * @return AddressClaimSet object
     */
    public AddressClaimSet getAddress();
    
    /**
     * Get the profile update timestamp claim (updated_at)
     * @return Update timestamp
     */
    public Long getUpdatedAt();
    
    /**
     * Get the authentication time claim (auth_time)
     * @return Authentication timestamp
     */
    public Long getAuthTime();
    
    /**
     * Get the nonce claim (nonce)
     * @return Nonce value
     */
    public String getNonce();
    
    /**
     * Get the authentication context class reference (acr)
     * @return ACR value
     */
    public String getAcr();
    
    /**
     * Get the authentication methods references (amr)
     * @return Array of AMR values
     */
    public String[] getAmr();
    
    /**
     * Get the authorized party claim (azp)
     * @return Authorized party identifier
     */
    public String getAuthorizedParty();
    
    /**
     * Get the access token hash claim (at_hash)
     * @return Access token hash
     */
    public String getAccessTokenHash();
    
    /**
     * Get the code hash claim (c_hash)
     * @return Authorization code hash
     */
    public String getCodeHash();
}

Refresh Token

OAuth2 refresh token representation.

/**
 * OAuth2 refresh token representation
 */
public class RefreshToken extends JsonWebToken {
    /**
     * Get the token type (typ claim)
     * @return Token type identifier
     */
    public String getType();
    
    /**
     * Get the scope claim
     * @return Space-separated scope values
     */
    public String getScope();
    
    /**
     * Check if this is an offline token
     * @return true if offline access token
     */
    public boolean isOfflineToken();
}

Logout Token

Backchannel logout token representation.

/**
 * Logout token for backchannel logout
 */
public class LogoutToken extends JsonWebToken {
    /**
     * Get the logout token events claim (events)
     * @return Events map
     */
    public Map<String, Object> getEvents();
    
    /**
     * Get the session ID claim (sid)
     * @return Session identifier
     */
    public String getSessionId();
    
    /**
     * Check if this is a logout event
     * @return true if contains logout event
     */
    public boolean isLogoutEvent();
}

Response Representations

Token endpoint and API response representations.

/**
 * OAuth2 token endpoint response
 */
public class AccessTokenResponse {
    /**
     * Get the access token
     * @return Access token string
     */
    public String getToken();
    
    /**
     * Get the token type (usually "Bearer")
     * @return Token type
     */
    public String getTokenType();
    
    /**
     * Get the refresh token
     * @return Refresh token string
     */
    public String getRefreshToken();
    
    /**
     * Get the ID token
     * @return ID token string
     */
    public String getIdToken();
    
    /**
     * Get the token expiration time in seconds
     * @return Expiration time
     */
    public Long getExpiresIn();
    
    /**
     * Get the refresh token expiration time in seconds
     * @return Refresh expiration time
     */
    public Long getRefreshExpiresIn();
    
    /**
     * Get the granted scope
     * @return Space-separated scope values
     */
    public String getScope();
    
    /**
     * Get the session state
     * @return Session state value
     */
    public String getSessionState();
    
    /**
     * Get error code (if response contains error)
     * @return Error code
     */
    public String getError();
    
    /**
     * Get error description (if response contains error)
     * @return Error description
     */
    public String getErrorDescription();
    
    /**
     * Get error URI (if response contains error)
     * @return Error URI
     */
    public String getErrorUri();
    
    /**
     * Get custom response parameter
     * @param name Parameter name
     * @return Parameter value
     */
    public Object getOtherParam(String name);
}

/**
 * OAuth2 device authorization response
 */
public class OAuth2DeviceAuthorizationResponse {
    /**
     * Get the device code
     * @return Device code string
     */
    public String getDeviceCode();
    
    /**
     * Get the user code
     * @return User code string
     */
    public String getUserCode();
    
    /**
     * Get the verification URI
     * @return Verification URI
     */
    public String getVerificationUri();
    
    /**
     * Get the complete verification URI
     * @return Complete verification URI with user code
     */
    public String getVerificationUriComplete();
    
    /**
     * Get the expiration time in seconds
     * @return Expiration time
     */
    public Integer getExpiresIn();
    
    /**
     * Get the polling interval in seconds
     * @return Polling interval
     */
    public Integer getInterval();
}

/**
 * OIDC UserInfo endpoint response
 */
public class UserInfo {
    /**
     * Get the subject claim (sub)
     * @return Subject identifier
     */
    public String getSubject();
    
    /**
     * Get the preferred username
     * @return Preferred username
     */
    public String getPreferredUsername();
    
    /**
     * Get the email address
     * @return Email address
     */
    public String getEmail();
    
    /**
     * Get the email verification status
     * @return Email verification status
     */
    public Boolean getEmailVerified();
    
    /**
     * Get the full name
     * @return Full name
     */
    public String getName();
    
    /**
     * Get the given name
     * @return Given/first name
     */
    public String getGivenName();
    
    /**
     * Get the family name
     * @return Family/last name
     */
    public String getFamilyName();
    
    /**
     * Get custom UserInfo claim
     * @param name Claim name
     * @return Claim value
     */
    public Object getClaim(String name);
    
    /**
     * Get all claims
     * @return Map of all claims
     */
    public Map<String, Object> getClaims();
}

Claims and Address Representations

/**
 * OIDC address claim representation
 */
public class AddressClaimSet {
    /**
     * Get the formatted address
     * @return Complete formatted address
     */
    public String getFormatted();
    
    /**
     * Get the street address
     * @return Street address
     */
    public String getStreetAddress();
    
    /**
     * Get the locality (city)
     * @return Locality/city
     */
    public String getLocality();
    
    /**
     * Get the region (state/province)
     * @return Region/state
     */
    public String getRegion();
    
    /**
     * Get the postal code
     * @return Postal/zip code
     */
    public String getPostalCode();
    
    /**
     * Get the country
     * @return Country name or code
     */
    public String getCountry();
}

/**
 * Claims request representation for OIDC
 */
public class ClaimsRepresentation {
    /**
     * Get ID token claims requirements
     * @return Map of ID token claim requirements
     */
    public Map<String, ClaimRequirement> getIdToken();
    
    /**
     * Get UserInfo claims requirements
     * @return Map of UserInfo claim requirements
     */
    public Map<String, ClaimRequirement> getUserinfo();
    
    /**
     * Individual claim requirement
     */
    public static class ClaimRequirement {
        /**
         * Check if claim is essential
         * @return true if essential
         */
        public Boolean getEssential();
        
        /**
         * Get expected claim value
         * @return Expected value
         */
        public String getValue();
        
        /**
         * Get expected claim values
         * @return Array of expected values
         */
        public String[] getValues();
    }
}

/**
 * Authorization details for rich authorization requests
 */
public class AuthorizationDetailsJSONRepresentation {
    /**
     * Get the authorization details type
     * @return Type identifier
     */
    public String getType();
    
    /**
     * Get the locations
     * @return Array of location URIs
     */
    public String[] getLocations();
    
    /**
     * Get the actions
     * @return Array of action identifiers
     */
    public String[] getActions();
    
    /**
     * Get the data types
     * @return Array of data type identifiers
     */
    public String[] getDataTypes();
    
    /**
     * Get the identifier
     * @return Resource identifier
     */
    public String getIdentifier();
    
    /**
     * Get custom authorization detail parameter
     * @param name Parameter name
     * @return Parameter value
     */
    public Object getCustomParameter(String name);
}

DPoP (Demonstration of Proof-of-Possession)

/**
 * DPoP (Demonstration of Proof-of-Possession) token representation
 */
public class DPoP extends JsonWebToken {
    /**
     * Get the HTTP method (htm claim)
     * @return HTTP method
     */
    public String getHttpMethod();
    
    /**
     * Get the HTTP URI (htu claim)
     * @return HTTP URI
     */
    public String getHttpUri();
    
    /**
     * Get the access token hash (ath claim)
     * @return Access token hash
     */
    public String getAccessTokenHash();
    
    /**
     * Get the nonce (nonce claim)
     * @return Nonce value
     */
    public String getNonce();
}

Usage Examples

import org.keycloak.representations.*;
import org.keycloak.TokenVerifier;

// Working with Access Token
AccessToken accessToken = TokenVerifier.create(tokenString, AccessToken.class)
    .publicKey(publicKey)
    .verify();

// Check roles and permissions
String subject = accessToken.getSubject();
String scope = accessToken.getScope();

AccessToken.Access realmAccess = accessToken.getRealmAccess();
if (realmAccess != null && realmAccess.isUserInRole("admin")) {
    // Handle admin access
}

AccessToken.Access clientAccess = accessToken.getResourceAccess("my-client");
if (clientAccess != null && clientAccess.isUserInRole("manager")) {
    // Handle client-specific role
}

// Working with ID Token
IDToken idToken = TokenVerifier.create(idTokenString, IDToken.class)
    .publicKey(publicKey)
    .verify();

String email = idToken.getEmail();
String name = idToken.getName();
Boolean emailVerified = idToken.getEmailVerified();

AddressClaimSet address = idToken.getAddress();
if (address != null) {
    String city = address.getLocality();
    String country = address.getCountry();
}

// Working with token response
AccessTokenResponse response = // ... obtained from token endpoint
String accessTokenString = response.getToken();
String refreshTokenString = response.getRefreshToken();
String idTokenString = response.getIdToken();
Long expiresIn = response.getExpiresIn();

// Error handling
if (response.getError() != null) {
    String error = response.getError();
    String errorDescription = response.getErrorDescription();
    // Handle error
}

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