0
# Keycloak Adapter Core
1
2
Keycloak Adapter Core provides the core functionality for Keycloak OIDC/OAuth2 client adapters, enabling Java applications to integrate with Keycloak identity and access management services. It includes essential components for authentication flow handling, token management, security context management, and bearer token validation.
3
4
## Package Information
5
6
- **Package Name**: keycloak-adapter-core
7
- **Package Type**: Maven
8
- **Group ID**: org.keycloak
9
- **Language**: Java
10
- **Installation**:
11
```xml
12
<dependency>
13
<groupId>org.keycloak</groupId>
14
<artifactId>keycloak-adapter-core</artifactId>
15
<version>25.0.3</version>
16
</dependency>
17
```
18
19
## Core Imports
20
21
```java
22
import org.keycloak.adapters.KeycloakDeployment;
23
import org.keycloak.adapters.KeycloakDeploymentBuilder;
24
import org.keycloak.adapters.AdapterDeploymentContext;
25
import org.keycloak.adapters.AdapterTokenStore;
26
import org.keycloak.adapters.RefreshableKeycloakSecurityContext;
27
```
28
29
## Basic Usage
30
31
```java
32
import org.keycloak.adapters.*;
33
import java.io.InputStream;
34
35
// Build deployment configuration from JSON
36
InputStream configStream = getClass().getResourceAsStream("/keycloak.json");
37
KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(configStream);
38
39
// Create deployment context for single-tenant
40
AdapterDeploymentContext deploymentContext = new AdapterDeploymentContext(deployment);
41
42
// For multi-tenant scenarios with resolver
43
KeycloakConfigResolver resolver = facade -> {
44
// Custom resolution logic based on request
45
return resolveDeploymentForTenant(facade);
46
};
47
AdapterDeploymentContext multiTenantContext = new AdapterDeploymentContext(resolver);
48
49
// Bearer token authentication
50
BearerTokenRequestAuthenticator bearerAuth = new BearerTokenRequestAuthenticator(deployment);
51
AuthOutcome outcome = bearerAuth.authenticate(httpFacade);
52
53
if (outcome == AuthOutcome.AUTHENTICATED) {
54
AccessToken token = bearerAuth.getToken();
55
String principal = AdapterUtils.getPrincipalName(deployment, token);
56
}
57
```
58
59
## Architecture
60
61
Keycloak Adapter Core is built around several key components:
62
63
- **Deployment Management**: `KeycloakDeployment` and `KeycloakDeploymentBuilder` for configuration management
64
- **Context Management**: `AdapterDeploymentContext` for single/multi-tenant deployment resolution
65
- **Authentication**: Various authenticator classes for different authentication flows
66
- **Token Management**: `RefreshableKeycloakSecurityContext` for token lifecycle and refresh
67
- **Storage Abstraction**: `AdapterTokenStore` interface for token persistence strategies
68
- **HTTP Client**: `HttpClientBuilder` for secure HTTP communication with Keycloak server
69
- **Key Rotation**: Public key locators for token verification with key rotation support
70
71
## Capabilities
72
73
### Core Adapter Management
74
75
Essential deployment configuration and context management for Keycloak integration. Handles single-tenant and multi-tenant scenarios with comprehensive configuration options.
76
77
```java { .api }
78
public class KeycloakDeployment {
79
public boolean isConfigured();
80
public String getResourceName();
81
public String getRealm();
82
public String getAuthServerBaseUrl();
83
public boolean isBearerOnly();
84
public boolean isPublicClient();
85
public HttpClient getClient();
86
}
87
88
public class KeycloakDeploymentBuilder {
89
public static KeycloakDeployment build(InputStream is);
90
public static KeycloakDeployment build(AdapterConfig adapterConfig);
91
}
92
93
public class AdapterDeploymentContext {
94
public AdapterDeploymentContext(KeycloakDeployment deployment);
95
public AdapterDeploymentContext(KeycloakConfigResolver configResolver);
96
public KeycloakDeployment resolveDeployment(HttpFacade facade);
97
}
98
```
99
100
[Core Adapter Management](./core-adapters.md)
101
102
### Authentication and Security Context
103
104
Authentication flow handling with support for bearer tokens, basic authentication, and OAuth flows. Provides security context management with token refresh capabilities.
105
106
```java { .api }
107
public abstract class RequestAuthenticator {
108
public AuthChallenge getChallenge();
109
public AuthOutcome authenticate();
110
}
111
112
public class BearerTokenRequestAuthenticator {
113
public BearerTokenRequestAuthenticator(KeycloakDeployment deployment);
114
public AuthOutcome authenticate(HttpFacade exchange);
115
public AccessToken getToken();
116
public String getTokenString();
117
}
118
119
public class RefreshableKeycloakSecurityContext extends KeycloakSecurityContext {
120
public AccessToken getToken();
121
public String getTokenString();
122
public boolean refreshExpiredToken(boolean checkActive);
123
public void logout(KeycloakDeployment deployment);
124
}
125
```
126
127
[Authentication](./authentication.md)
128
129
### Token Storage and Management
130
131
Token storage abstraction and utilities for managing token lifecycle, including cookie-based storage and token refresh operations.
132
133
```java { .api }
134
public interface AdapterTokenStore {
135
void checkCurrentToken();
136
boolean isCached(RequestAuthenticator authenticator);
137
void saveAccountInfo(OidcKeycloakAccount account);
138
void logout();
139
void refreshCallback(RefreshableKeycloakSecurityContext securityContext);
140
}
141
142
public class CookieTokenStore {
143
public static void setTokenCookie(KeycloakDeployment deployment, HttpFacade facade, RefreshableKeycloakSecurityContext session);
144
public static KeycloakPrincipal<RefreshableKeycloakSecurityContext> getPrincipalFromCookie(KeycloakDeployment deployment, HttpFacade facade, AdapterTokenStore tokenStore);
145
public static void removeCookie(KeycloakDeployment deployment, HttpFacade facade);
146
}
147
```
148
149
[Token Storage](./token-storage.md)
150
151
### HTTP Client and Server Operations
152
153
HTTP client builder with SSL configuration and server request utilities for token operations, logout, and node registration.
154
155
```java { .api }
156
public class HttpClientBuilder {
157
public HttpClientBuilder socketTimeout(long timeout, TimeUnit unit);
158
public HttpClientBuilder sslContext(SSLContext sslContext);
159
public HttpClientBuilder trustStore(KeyStore truststore);
160
public HttpClient build();
161
}
162
163
public class ServerRequest {
164
public static void invokeLogout(KeycloakDeployment deployment, String refreshToken) throws IOException, HttpFailure;
165
public static AccessTokenResponse invokeRefresh(KeycloakDeployment deployment, String refreshToken) throws IOException, HttpFailure;
166
public static void invokeRegisterNode(KeycloakDeployment deployment, String host) throws HttpFailure, IOException;
167
}
168
```
169
170
[HTTP Operations](./http-operations.md)
171
172
### Key Rotation and Token Verification
173
174
Public key location and token verification utilities supporting key rotation for secure token validation.
175
176
```java { .api }
177
public interface PublicKeyLocator {
178
PublicKey getPublicKey(String kid, KeycloakDeployment deployment);
179
void reset(KeycloakDeployment deployment);
180
}
181
182
public class AdapterTokenVerifier {
183
public static AccessToken verifyToken(String tokenString, KeycloakDeployment deployment) throws VerificationException;
184
public static VerifiedTokens verifyTokens(String accessTokenString, String idTokenString, KeycloakDeployment deployment) throws VerificationException;
185
}
186
```
187
188
[Key Rotation](./key-rotation.md)
189
190
### JAAS Integration
191
192
JAAS (Java Authentication and Authorization Service) integration for enterprise Java applications with login modules and principal management.
193
194
```java { .api }
195
public abstract class AbstractKeycloakLoginModule implements LoginModule {
196
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options);
197
public boolean login() throws LoginException;
198
public boolean commit() throws LoginException;
199
public boolean logout() throws LoginException;
200
}
201
202
public class RolePrincipal implements Principal {
203
public RolePrincipal(String roleName);
204
public String getName();
205
}
206
```
207
208
[JAAS Integration](./jaas-integration.md)
209
210
### Policy Enforcement Point (PEP)
211
212
Policy Enforcement Point integration for authorization policy evaluation with Keycloak's authorization services.
213
214
```java { .api }
215
public class HttpAuthzRequest implements AuthzRequest {
216
public HttpAuthzRequest(OIDCHttpFacade oidcFacade);
217
public String getMethod();
218
public String getURI();
219
public List<String> getHeaders(String name);
220
public String getRemoteAddr();
221
}
222
223
public class HttpAuthzResponse implements AuthzResponse {
224
public HttpAuthzResponse(OIDCHttpFacade oidcFacade);
225
public void sendError(int statusCode);
226
public void setHeader(String name, String value);
227
}
228
```
229
230
[Policy Enforcement](./policy-enforcement.md)
231
232
### Utility Operations
233
234
Utility functions for common adapter operations including principal name resolution, role extraction, HTTP requests, and credential management.
235
236
```java { .api }
237
public class AdapterUtils {
238
public static String generateId();
239
public static Set<String> getRolesFromSecurityContext(RefreshableKeycloakSecurityContext session);
240
public static String getPrincipalName(KeycloakDeployment deployment, AccessToken token);
241
public static KeycloakPrincipal<RefreshableKeycloakSecurityContext> createPrincipal(KeycloakDeployment deployment, RefreshableKeycloakSecurityContext securityContext);
242
public static void setClientCredentials(KeycloakDeployment deployment, Map<String, String> headers, Map<String, String> params);
243
}
244
245
public class HttpAdapterUtils {
246
public static <T> T sendJsonHttpRequest(KeycloakDeployment deployment, HttpRequestBase httpRequest, Class<T> clazz) throws HttpClientAdapterException;
247
}
248
```
249
250
[Utility Operations](./utility-operations.md)
251
252
## Common Types
253
254
```java { .api }
255
public enum AuthOutcome {
256
AUTHENTICATED, NOT_ATTEMPTED, FAILED
257
}
258
259
public interface AuthChallenge {
260
boolean challenge(HttpFacade exchange);
261
int getResponseCode();
262
String getError();
263
String getErrorDescription();
264
}
265
266
public class OIDCAuthenticationError {
267
public enum Reason {
268
NO_BEARER_TOKEN, INVALID_STATE_COOKIE, OAUTH_ERROR,
269
SSL_REQUIRED, CODE_TO_TOKEN_FAILURE, INVALID_TOKEN,
270
STALE_TOKEN, NO_AUTHORIZATION_HEADER
271
}
272
273
public OIDCAuthenticationError(Reason reason, String description);
274
public Reason getReason();
275
public String getDescription();
276
}
277
278
public class HttpClientAdapterException extends Exception {
279
public HttpClientAdapterException(String message);
280
public HttpClientAdapterException(String message, Throwable t);
281
}
282
283
public interface CorsHeaders {
284
String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
285
String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
286
String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
287
String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
288
String ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age";
289
String ORIGIN = "Origin";
290
String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method";
291
String ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers";
292
String ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers";
293
}
294
```