0
# Utility Operations
1
2
Utility functions for common adapter operations including principal name resolution, role extraction, HTTP requests, and credential management.
3
4
## Capabilities
5
6
### AdapterUtils
7
8
Core utility functions for adapter operations and principal management.
9
10
```java { .api }
11
/**
12
* Core utility functions for adapter operations and principal management
13
*/
14
public class AdapterUtils {
15
/**
16
* Generate a unique identifier
17
* @return Randomly generated UUID string
18
*/
19
public static String generateId();
20
21
/**
22
* Extract roles from security context based on deployment configuration
23
* @param session Refreshable security context containing tokens
24
* @return Set of role names, empty set if no roles found
25
*/
26
public static Set<String> getRolesFromSecurityContext(RefreshableKeycloakSecurityContext session);
27
28
/**
29
* Get principal name from access token based on deployment attribute configuration
30
* @param deployment Keycloak deployment configuration
31
* @param token Access token containing user information
32
* @return Principal name extracted from token, defaults to subject if configured attribute not found
33
*/
34
public static String getPrincipalName(KeycloakDeployment deployment, AccessToken token);
35
36
/**
37
* Create a Keycloak principal from deployment and security context
38
* @param deployment Keycloak deployment configuration
39
* @param securityContext Security context containing token information
40
* @return KeycloakPrincipal instance with resolved principal name
41
*/
42
public static KeycloakPrincipal<RefreshableKeycloakSecurityContext> createPrincipal(
43
KeycloakDeployment deployment,
44
RefreshableKeycloakSecurityContext securityContext
45
);
46
47
/**
48
* Set client credentials in request headers and parameters
49
* @param deployment Keycloak deployment configuration
50
* @param headers Map to populate with credential headers
51
* @param params Map to populate with credential parameters
52
*/
53
public static void setClientCredentials(
54
KeycloakDeployment deployment,
55
Map<String, String> headers,
56
Map<String, String> params
57
);
58
}
59
```
60
61
**Usage Examples:**
62
63
```java
64
// Generate unique identifier for state parameters
65
String state = AdapterUtils.generateId();
66
67
// Extract roles from authenticated user
68
RefreshableKeycloakSecurityContext securityContext = getSecurityContext();
69
Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext);
70
71
// Check for specific role
72
if (roles.contains("admin")) {
73
// Allow admin operations
74
}
75
76
// Get principal name based on deployment configuration
77
AccessToken token = securityContext.getToken();
78
String principalName = AdapterUtils.getPrincipalName(deployment, token);
79
80
// Create principal for security frameworks
81
KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal =
82
AdapterUtils.createPrincipal(deployment, securityContext);
83
84
// Set client credentials for HTTP requests
85
Map<String, String> headers = new HashMap<>();
86
Map<String, String> params = new HashMap<>();
87
AdapterUtils.setClientCredentials(deployment, headers, params);
88
89
// Apply credentials to HTTP request
90
for (Map.Entry<String, String> header : headers.entrySet()) {
91
httpRequest.setHeader(header.getKey(), header.getValue());
92
}
93
```
94
95
### HttpAdapterUtils
96
97
HTTP utility functions for JSON communication with Keycloak server.
98
99
```java { .api }
100
/**
101
* HTTP utility functions for JSON communication with Keycloak server
102
*/
103
public class HttpAdapterUtils {
104
/**
105
* Send HTTP request expecting JSON response
106
* @param deployment Keycloak deployment configuration with HTTP client
107
* @param httpRequest Configured HTTP request to execute
108
* @param clazz Expected response type class
109
* @param <T> Response type
110
* @return Deserialized response object
111
* @throws HttpClientAdapterException if HTTP request fails or response cannot be parsed
112
*/
113
public static <T> T sendJsonHttpRequest(
114
KeycloakDeployment deployment,
115
HttpRequestBase httpRequest,
116
Class<T> clazz
117
) throws HttpClientAdapterException;
118
}
119
```
120
121
**Usage Examples:**
122
123
```java
124
// Create HTTP request for token introspection
125
HttpPost tokenRequest = new HttpPost(deployment.getTokenIntrospectionUrl());
126
tokenRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
127
128
// Set form parameters
129
List<NameValuePair> params = new ArrayList<>();
130
params.add(new BasicNameValuePair("token", accessTokenString));
131
params.add(new BasicNameValuePair("token_type_hint", "access_token"));
132
tokenRequest.setEntity(new UrlEncodedFormEntity(params));
133
134
// Set client credentials
135
AdapterUtils.setClientCredentials(deployment, tokenRequest, new ArrayList<>());
136
137
try {
138
// Execute request and parse JSON response
139
TokenIntrospectionResponse response = HttpAdapterUtils.sendJsonHttpRequest(
140
deployment, tokenRequest, TokenIntrospectionResponse.class
141
);
142
143
if (response.getActive()) {
144
// Token is active
145
String username = response.getUsername();
146
Set<String> scopes = response.getScope();
147
}
148
} catch (HttpClientAdapterException e) {
149
// Handle request failure
150
logger.error("Token introspection failed", e);
151
}
152
153
// Example with user info endpoint
154
HttpGet userInfoRequest = new HttpGet(deployment.getUserInfoUrl());
155
userInfoRequest.setHeader("Authorization", "Bearer " + accessTokenString);
156
157
try {
158
UserInfo userInfo = HttpAdapterUtils.sendJsonHttpRequest(
159
deployment, userInfoRequest, UserInfo.class
160
);
161
162
String email = userInfo.getEmail();
163
String name = userInfo.getName();
164
} catch (HttpClientAdapterException e) {
165
// Handle user info request failure
166
logger.error("User info request failed", e);
167
}
168
```
169
170
### PreAuthActionsHandler
171
172
Handler for pre-authentication actions like node registration, logout notifications, and admin requests.
173
174
```java { .api }
175
/**
176
* Handler for pre-authentication actions and administrative requests
177
*/
178
public class PreAuthActionsHandler {
179
/**
180
* Constructor for pre-authentication actions handler
181
* @param userSessionManagement User session management implementation
182
* @param deploymentContext Adapter deployment context
183
* @param facade HTTP facade for request/response handling
184
*/
185
public PreAuthActionsHandler(
186
UserSessionManagement userSessionManagement,
187
AdapterDeploymentContext deploymentContext,
188
HttpFacade facade
189
);
190
191
/**
192
* Handle request if it matches a pre-authentication action
193
* @return true if request was handled, false if normal processing should continue
194
*/
195
public boolean handleRequest();
196
}
197
```
198
199
**Usage Examples:**
200
201
```java
202
// Handle pre-authentication actions before normal auth flow
203
PreAuthActionsHandler preAuthHandler = new PreAuthActionsHandler(
204
userSessionManagement, deploymentContext, httpFacade
205
);
206
207
if (preAuthHandler.handleRequest()) {
208
// Request was handled (e.g., admin logout, node registration)
209
// Response has been sent, no further processing needed
210
return;
211
}
212
213
// Continue with normal authentication flow
214
RequestAuthenticator authenticator = createAuthenticator(facade, deployment);
215
AuthOutcome outcome = authenticator.authenticate();
216
```
217
218
### NodesRegistrationManagement
219
220
Management of cluster node registration with Keycloak server for distributed deployments.
221
222
```java { .api }
223
/**
224
* Management of cluster node registration with Keycloak server
225
*/
226
public class NodesRegistrationManagement {
227
/**
228
* Get node registration management instance
229
* @return NodesRegistrationManagement singleton instance
230
*/
231
public static NodesRegistrationManagement getInstance();
232
233
/**
234
* Try to register node with Keycloak server
235
* @param deployment Keycloak deployment configuration
236
*/
237
public void tryRegister(KeycloakDeployment deployment);
238
}
239
```
240
241
**Usage Examples:**
242
243
```java
244
// Register application node with Keycloak for admin operations
245
NodesRegistrationManagement nodeManager = NodesRegistrationManagement.getInstance();
246
247
// Register during application startup
248
nodeManager.tryRegister(deployment);
249
250
// Registration typically happens automatically, but can be triggered manually
251
// This enables admin console operations like logout all users
252
```
253
254
### SniSSLSocketFactory
255
256
SSL socket factory with Server Name Indication (SNI) support for secure HTTP connections.
257
258
```java { .api }
259
/**
260
* SSL socket factory with Server Name Indication (SNI) support
261
*/
262
public class SniSSLSocketFactory extends SSLSocketFactory {
263
/**
264
* Constructor with SSL context and hostname verifier
265
* @param sslContext SSL context for secure connections
266
* @param hostnameVerifier Hostname verification strategy
267
*/
268
public SniSSLSocketFactory(SSLContext sslContext, X509HostnameVerifier hostnameVerifier);
269
270
/**
271
* Create SSL socket with SNI support
272
* @param socket Base socket for SSL wrapping
273
* @param host Target hostname for SNI
274
* @param port Target port
275
* @param autoClose Whether to auto-close underlying socket
276
* @return SSL socket with SNI configuration
277
* @throws IOException if socket creation fails
278
*/
279
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException;
280
}
281
```
282
283
**Usage Examples:**
284
285
```java
286
// Create SSL context with custom trust store
287
SSLContext sslContext = SSLContext.getInstance("TLS");
288
sslContext.init(null, trustManagers, new SecureRandom());
289
290
// Create SNI-enabled SSL socket factory
291
SniSSLSocketFactory sslSocketFactory = new SniSSLSocketFactory(
292
sslContext,
293
SSLSocketFactory.STRICT_HOSTNAME_VERIFIER
294
);
295
296
// Configure HTTP client with SNI support
297
HttpClient httpClient = HttpClientBuilder.create()
298
.setSSLSocketFactory(sslSocketFactory)
299
.build();
300
301
// Use in deployment configuration
302
KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(config);
303
deployment.setClient(httpClient);
304
```