0
# Token Management
1
2
Core JWT token creation, validation, and processing with support for access tokens, ID tokens, refresh tokens, and specialized Keycloak token types.
3
4
## Capabilities
5
6
### TokenVerifier
7
8
Flexible JWT token validation system with configurable verification checks and support for various signature algorithms.
9
10
```java { .api }
11
/**
12
* Generic JWT token verifier with pluggable verification predicates
13
* @param <T> Token type extending JsonWebToken
14
*/
15
public class TokenVerifier<T extends JsonWebToken> {
16
/**
17
* Create a token verifier instance for the specified token string and type
18
* @param tokenString Raw JWT token string
19
* @param clazz Token class type
20
* @return TokenVerifier instance
21
*/
22
public static <T extends JsonWebToken> TokenVerifier<T> create(String tokenString, Class<T> clazz);
23
24
/**
25
* Add default verification checks (expiration, not-before, issued-at)
26
* @return TokenVerifier instance for chaining
27
*/
28
public TokenVerifier<T> withDefaultChecks();
29
30
/**
31
* Set public key for signature verification
32
* @param publicKey Public key for RSA/ECDSA verification
33
* @return TokenVerifier instance for chaining
34
*/
35
public TokenVerifier<T> publicKey(PublicKey publicKey);
36
37
/**
38
* Set secret key for HMAC signature verification
39
* @param secretKey Secret key for HMAC verification
40
* @return TokenVerifier instance for chaining
41
*/
42
public TokenVerifier<T> secretKey(SecretKey secretKey);
43
44
/**
45
* Set expected audience claim values
46
* @param audience Expected audience values
47
* @return TokenVerifier instance for chaining
48
*/
49
public TokenVerifier<T> audience(String... audience);
50
51
/**
52
* Set expected issued-for claim value
53
* @param issuedFor Expected azp/client_id claim value
54
* @return TokenVerifier instance for chaining
55
*/
56
public TokenVerifier<T> issuedFor(String issuedFor);
57
58
/**
59
* Add custom verification predicates
60
* @param checks Custom verification predicates
61
* @return TokenVerifier instance for chaining
62
*/
63
@SafeVarargs
64
public final TokenVerifier<T> withChecks(Predicate<T>... checks);
65
66
/**
67
* Perform token verification
68
* @return TokenVerifier instance for chaining (call getToken() to get verified token)
69
* @throws VerificationException if verification fails
70
*/
71
public TokenVerifier<T> verify() throws VerificationException;
72
73
/**
74
* Get the verified token instance
75
* @return Token instance
76
* @throws VerificationException if token parsing fails
77
*/
78
public T getToken() throws VerificationException;
79
80
/**
81
* Get the token header without verification
82
* @return Token header
83
*/
84
public JWSHeader getHeader();
85
}
86
```
87
88
**Usage Examples:**
89
90
```java
91
import org.keycloak.TokenVerifier;
92
import org.keycloak.representations.AccessToken;
93
import org.keycloak.representations.IDToken;
94
import org.keycloak.common.VerificationException;
95
import org.keycloak.exceptions.TokenNotActiveException;
96
import org.keycloak.exceptions.TokenSignatureInvalidException;
97
import java.security.PublicKey;
98
99
// Basic access token verification
100
try {
101
AccessToken accessToken = TokenVerifier.create(tokenString, AccessToken.class)
102
.withDefaultChecks()
103
.publicKey(rsaPublicKey)
104
.audience("my-client-id")
105
.verify()
106
.getToken();
107
108
// Token is valid, extract information
109
String subject = accessToken.getSubject();
110
String scope = accessToken.getScope();
111
Set<String> roles = accessToken.getRealmAccess().getRoles();
112
113
} catch (VerificationException e) {
114
// Handle verification failure
115
System.err.println("Token verification failed: " + e.getMessage());
116
}
117
118
// ID token verification with custom checks
119
IDToken idToken = TokenVerifier.create(idTokenString, IDToken.class)
120
.withDefaultChecks()
121
.publicKey(publicKey)
122
.audience("web-client")
123
.withChecks(token -> {
124
// Custom check: ensure email is verified
125
return Boolean.TRUE.equals(token.getEmailVerified());
126
})
127
.verify()
128
.getToken();
129
130
// HMAC token verification
131
AccessToken hmacToken = TokenVerifier.create(tokenString, AccessToken.class)
132
.withDefaultChecks()
133
.secretKey(hmacSecretKey)
134
.verify()
135
.getToken();
136
```
137
138
### Custom Verification Predicates
139
140
Built-in and custom verification predicates for advanced token validation scenarios.
141
142
```java { .api }
143
/**
144
* Custom verification predicate interface
145
* @param <T> Token type
146
*/
147
public interface Predicate<T> {
148
/**
149
* Test the token against custom criteria
150
* @param token Token to test
151
* @return true if verification passes
152
* @throws TokenVerificationException if verification fails
153
*/
154
boolean test(T token) throws TokenVerificationException;
155
}
156
157
/**
158
* Built-in verification predicates
159
*/
160
public static class TokenVerifier {
161
/**
162
* Realm URL verification predicate
163
*/
164
public static class RealmUrlCheck implements Predicate<JsonWebToken> {
165
public RealmUrlCheck(String realmUrl);
166
public boolean test(JsonWebToken token) throws TokenVerificationException;
167
}
168
169
/**
170
* Token type verification predicate
171
*/
172
public static class TokenTypeCheck implements Predicate<JsonWebToken> {
173
public TokenTypeCheck(String expectedType);
174
public boolean test(JsonWebToken token) throws TokenVerificationException;
175
}
176
177
/**
178
* Audience verification predicate
179
*/
180
public static class AudienceCheck implements Predicate<JsonWebToken> {
181
public AudienceCheck(String... expectedAudience);
182
public boolean test(JsonWebToken token) throws TokenVerificationException;
183
}
184
185
/**
186
* Issued-for verification predicate
187
*/
188
public static class IssuedForCheck implements Predicate<JsonWebToken> {
189
public IssuedForCheck(String expectedIssuedFor);
190
public boolean test(JsonWebToken token) throws TokenVerificationException;
191
}
192
}
193
```
194
195
### Token Interface
196
197
Base token interface and category system for all JWT token types.
198
199
```java { .api }
200
/**
201
* Base marker interface for all token types
202
*/
203
public interface Token {
204
/**
205
* Get the token category
206
* @return Token category enum value
207
*/
208
TokenCategory getCategory();
209
}
210
211
/**
212
* Token category enumeration for classifying different token types
213
*/
214
public enum TokenCategory {
215
/** Internal system tokens */
216
INTERNAL,
217
/** OAuth2 access tokens */
218
ACCESS,
219
/** OpenID Connect ID tokens */
220
ID,
221
/** Administrative tokens */
222
ADMIN,
223
/** UserInfo endpoint tokens */
224
USERINFO,
225
/** Logout tokens */
226
LOGOUT,
227
/** Authorization response tokens */
228
AUTHORIZATION_RESPONSE
229
}
230
```
231
232
### KeyPairVerifier
233
234
RSA key pair verification utility for validating public/private key relationships.
235
236
```java { .api }
237
/**
238
* Utility for verifying RSA key pair relationships
239
*/
240
public class KeyPairVerifier {
241
/**
242
* Verify that a public and private key form a valid RSA key pair
243
* @param privateKey RSA private key
244
* @param publicKey RSA public key
245
* @return true if keys form a valid pair
246
*/
247
public static boolean verify(PrivateKey privateKey, PublicKey publicKey);
248
}
249
```
250
251
### RSATokenVerifier
252
253
Legacy RSA-specific token verification utility (deprecated in favor of TokenVerifier).
254
255
```java { .api }
256
/**
257
* Legacy RSA token verifier utility
258
* @deprecated Use TokenVerifier with publicKey() method instead
259
*/
260
@Deprecated
261
public class RSATokenVerifier {
262
/**
263
* Verify RSA-signed token
264
* @param token Token string
265
* @param publicKey RSA public key
266
* @return Parsed access token
267
* @throws TokenVerificationException if verification fails
268
*/
269
public static AccessToken verifyToken(String token, PublicKey publicKey)
270
throws TokenVerificationException;
271
}
272
```
273
274
### TokenIdGenerator
275
276
Utility for generating unique token identifiers.
277
278
```java { .api }
279
/**
280
* Token ID generation utility
281
*/
282
public class TokenIdGenerator {
283
/**
284
* Generate a unique token identifier
285
* @return Unique token ID string
286
*/
287
public static String generateId();
288
289
/**
290
* Generate a unique token identifier with custom prefix
291
* @param prefix Custom prefix for the token ID
292
* @return Unique token ID string with prefix
293
*/
294
public static String generateId(String prefix);
295
}
296
```
297
298
## Exception Handling
299
300
### Token Verification Exceptions
301
302
```java { .api }
303
/**
304
* Base exception for token verification failures
305
*/
306
public class TokenVerificationException extends Exception {
307
public TokenVerificationException(String message);
308
public TokenVerificationException(String message, Throwable cause);
309
public TokenVerificationException(JsonWebToken token, String message);
310
public TokenVerificationException(JsonWebToken token, String message, Throwable cause);
311
312
/**
313
* Get the token that failed verification (if available)
314
* @return Token instance or null
315
*/
316
public JsonWebToken getToken();
317
}
318
319
/**
320
* Exception thrown when token is not active (expired or not yet valid)
321
*/
322
public class TokenNotActiveException extends TokenVerificationException {
323
public TokenNotActiveException(JsonWebToken token, String message);
324
}
325
326
/**
327
* Exception thrown when token signature is invalid
328
*/
329
public class TokenSignatureInvalidException extends TokenVerificationException {
330
public TokenSignatureInvalidException(JsonWebToken token, String message);
331
}
332
```
333
334
**Usage Examples:**
335
336
```java
337
try {
338
AccessToken token = TokenVerifier.create(tokenString, AccessToken.class)
339
.withDefaultChecks()
340
.publicKey(publicKey)
341
.verify()
342
.getToken();
343
344
} catch (TokenNotActiveException e) {
345
// Token is expired or not yet valid
346
System.err.println("Token is not active: " + e.getMessage());
347
348
} catch (TokenSignatureInvalidException e) {
349
// Token signature verification failed
350
System.err.println("Invalid token signature: " + e.getMessage());
351
352
} catch (TokenVerificationException e) {
353
// Other verification failures
354
System.err.println("Token verification failed: " + e.getMessage());
355
}
356
```