0
# Token Representations
1
2
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.
3
4
## Capabilities
5
6
### Base JWT Token
7
8
Foundation class for all JWT token types with standard claims support.
9
10
```java { .api }
11
/**
12
* Base JWT implementation with standard RFC 7519 claims
13
*/
14
public class JsonWebToken implements Token {
15
/**
16
* Check if token is expired
17
* @return true if current time is past expiration
18
*/
19
public boolean isExpired();
20
21
/**
22
* Check if token is active (not expired and not before time has passed)
23
* @return true if token is currently valid for time-based checks
24
*/
25
public boolean isActive();
26
27
/**
28
* Get the issuer claim (iss)
29
* @return Issuer identifier
30
*/
31
public String getIssuer();
32
33
/**
34
* Get the subject claim (sub)
35
* @return Subject identifier
36
*/
37
public String getSubject();
38
39
/**
40
* Get the audience claim (aud) as array
41
* @return Array of audience values
42
*/
43
public String[] getAudience();
44
45
/**
46
* Check if token has specific audience
47
* @param audience Audience to check
48
* @return true if audience is present
49
*/
50
public boolean hasAudience(String audience);
51
52
/**
53
* Get the expiration time claim (exp)
54
* @return Expiration timestamp
55
*/
56
public Long getExpiration();
57
58
/**
59
* Get the not-before time claim (nbf)
60
* @return Not-before timestamp
61
*/
62
public Long getNotBefore();
63
64
/**
65
* Get the issued-at time claim (iat)
66
* @return Issued-at timestamp
67
*/
68
public Long getIssuedAt();
69
70
/**
71
* Get the JWT ID claim (jti)
72
* @return JWT identifier
73
*/
74
public String getId();
75
76
/**
77
* Get all other claims not covered by standard methods
78
* @return Map of additional claims
79
*/
80
public Map<String, Object> getOtherClaims();
81
82
/**
83
* Get the token category for classification
84
* @return TokenCategory enum value
85
*/
86
public TokenCategory getCategory();
87
}
88
```
89
90
### Access Token
91
92
OAuth2 access token with Keycloak extensions for roles and permissions.
93
94
```java { .api }
95
/**
96
* OAuth2 access token with Keycloak role and permission extensions
97
*/
98
public class AccessToken extends JsonWebToken {
99
/**
100
* Get the scope claim
101
* @return Space-separated scope values
102
*/
103
public String getScope();
104
105
/**
106
* Get the session state identifier
107
* @return Session state value
108
*/
109
public String getSessionState();
110
111
/**
112
* Get allowed origins for CORS
113
* @return Set of allowed origin URLs
114
*/
115
public Set<String> getAllowedOrigins();
116
117
/**
118
* Get realm-level access information
119
* @return Access object with realm roles
120
*/
121
public Access getRealmAccess();
122
123
/**
124
* Get resource-level access information for all resources
125
* @return Map of resource name to Access object
126
*/
127
public Map<String, Access> getResourceAccess();
128
129
/**
130
* Get resource-level access information for specific resource
131
* @param resource Resource name
132
* @return Access object or null if not found
133
*/
134
public Access getResourceAccess(String resource);
135
136
/**
137
* Get authorization information (UMA permissions)
138
* @return Authorization object with permissions
139
*/
140
public Authorization getAuthorization();
141
142
/**
143
* Get the trusted certificates
144
* @return Set of trusted certificate identifiers
145
*/
146
public Set<String> getTrustedCertificates();
147
148
/**
149
* Access control information for roles and permissions
150
*/
151
public static class Access {
152
/**
153
* Get all roles
154
* @return Set of role names
155
*/
156
public Set<String> getRoles();
157
158
/**
159
* Check if user has specific role
160
* @param role Role name to check
161
* @return true if role is present
162
*/
163
public boolean isUserInRole(String role);
164
165
/**
166
* Verify user has specific role (throws exception if not)
167
* @param role Role name to verify
168
* @throws AccessDeniedException if role not present
169
*/
170
public void verify(String role) throws AccessDeniedException;
171
172
/**
173
* Add role to the access object
174
* @param roleName Role name to add
175
*/
176
public void addRole(String roleName);
177
}
178
179
/**
180
* Authorization information for UMA permissions
181
*/
182
public static class Authorization {
183
/**
184
* Get all permissions
185
* @return List of Permission objects
186
*/
187
public List<Permission> getPermissions();
188
189
/**
190
* Check if user has permission for resource and scope
191
* @param resource Resource identifier
192
* @param scope Scope identifier
193
* @return true if permission exists
194
*/
195
public boolean hasPermission(String resource, String scope);
196
197
/**
198
* Get permissions for specific resource
199
* @param resource Resource identifier
200
* @return List of permissions for the resource
201
*/
202
public List<Permission> getPermissions(String resource);
203
}
204
}
205
```
206
207
### ID Token
208
209
OpenID Connect ID token with standard OIDC claims.
210
211
```java { .api }
212
/**
213
* OpenID Connect ID token with standard profile claims
214
*/
215
public class IDToken extends JsonWebToken {
216
/**
217
* Get the full name claim (name)
218
* @return Full name
219
*/
220
public String getName();
221
222
/**
223
* Get the given name claim (given_name)
224
* @return Given/first name
225
*/
226
public String getGivenName();
227
228
/**
229
* Get the family name claim (family_name)
230
* @return Family/last name
231
*/
232
public String getFamilyName();
233
234
/**
235
* Get the middle name claim (middle_name)
236
* @return Middle name
237
*/
238
public String getMiddleName();
239
240
/**
241
* Get the nickname claim (nickname)
242
* @return Nickname
243
*/
244
public String getNickname();
245
246
/**
247
* Get the preferred username claim (preferred_username)
248
* @return Preferred username
249
*/
250
public String getPreferredUsername();
251
252
/**
253
* Get the profile URL claim (profile)
254
* @return Profile page URL
255
*/
256
public String getProfile();
257
258
/**
259
* Get the picture URL claim (picture)
260
* @return Profile picture URL
261
*/
262
public String getPicture();
263
264
/**
265
* Get the website URL claim (website)
266
* @return Website URL
267
*/
268
public String getWebsite();
269
270
/**
271
* Get the email address claim (email)
272
* @return Email address
273
*/
274
public String getEmail();
275
276
/**
277
* Get the email verification status claim (email_verified)
278
* @return Email verification status
279
*/
280
public Boolean getEmailVerified();
281
282
/**
283
* Get the gender claim (gender)
284
* @return Gender value
285
*/
286
public String getGender();
287
288
/**
289
* Get the birthdate claim (birthdate)
290
* @return Birthdate string (YYYY-MM-DD format)
291
*/
292
public String getBirthdate();
293
294
/**
295
* Get the timezone claim (zoneinfo)
296
* @return Timezone identifier
297
*/
298
public String getZoneinfo();
299
300
/**
301
* Get the locale claim (locale)
302
* @return Locale identifier
303
*/
304
public String getLocale();
305
306
/**
307
* Get the phone number claim (phone_number)
308
* @return Phone number
309
*/
310
public String getPhoneNumber();
311
312
/**
313
* Get the phone verification status claim (phone_number_verified)
314
* @return Phone verification status
315
*/
316
public Boolean getPhoneNumberVerified();
317
318
/**
319
* Get the address claim (address)
320
* @return AddressClaimSet object
321
*/
322
public AddressClaimSet getAddress();
323
324
/**
325
* Get the profile update timestamp claim (updated_at)
326
* @return Update timestamp
327
*/
328
public Long getUpdatedAt();
329
330
/**
331
* Get the authentication time claim (auth_time)
332
* @return Authentication timestamp
333
*/
334
public Long getAuthTime();
335
336
/**
337
* Get the nonce claim (nonce)
338
* @return Nonce value
339
*/
340
public String getNonce();
341
342
/**
343
* Get the authentication context class reference (acr)
344
* @return ACR value
345
*/
346
public String getAcr();
347
348
/**
349
* Get the authentication methods references (amr)
350
* @return Array of AMR values
351
*/
352
public String[] getAmr();
353
354
/**
355
* Get the authorized party claim (azp)
356
* @return Authorized party identifier
357
*/
358
public String getAuthorizedParty();
359
360
/**
361
* Get the access token hash claim (at_hash)
362
* @return Access token hash
363
*/
364
public String getAccessTokenHash();
365
366
/**
367
* Get the code hash claim (c_hash)
368
* @return Authorization code hash
369
*/
370
public String getCodeHash();
371
}
372
```
373
374
### Refresh Token
375
376
OAuth2 refresh token representation.
377
378
```java { .api }
379
/**
380
* OAuth2 refresh token representation
381
*/
382
public class RefreshToken extends JsonWebToken {
383
/**
384
* Get the token type (typ claim)
385
* @return Token type identifier
386
*/
387
public String getType();
388
389
/**
390
* Get the scope claim
391
* @return Space-separated scope values
392
*/
393
public String getScope();
394
395
/**
396
* Check if this is an offline token
397
* @return true if offline access token
398
*/
399
public boolean isOfflineToken();
400
}
401
```
402
403
### Logout Token
404
405
Backchannel logout token representation.
406
407
```java { .api }
408
/**
409
* Logout token for backchannel logout
410
*/
411
public class LogoutToken extends JsonWebToken {
412
/**
413
* Get the logout token events claim (events)
414
* @return Events map
415
*/
416
public Map<String, Object> getEvents();
417
418
/**
419
* Get the session ID claim (sid)
420
* @return Session identifier
421
*/
422
public String getSessionId();
423
424
/**
425
* Check if this is a logout event
426
* @return true if contains logout event
427
*/
428
public boolean isLogoutEvent();
429
}
430
```
431
432
### Response Representations
433
434
Token endpoint and API response representations.
435
436
```java { .api }
437
/**
438
* OAuth2 token endpoint response
439
*/
440
public class AccessTokenResponse {
441
/**
442
* Get the access token
443
* @return Access token string
444
*/
445
public String getToken();
446
447
/**
448
* Get the token type (usually "Bearer")
449
* @return Token type
450
*/
451
public String getTokenType();
452
453
/**
454
* Get the refresh token
455
* @return Refresh token string
456
*/
457
public String getRefreshToken();
458
459
/**
460
* Get the ID token
461
* @return ID token string
462
*/
463
public String getIdToken();
464
465
/**
466
* Get the token expiration time in seconds
467
* @return Expiration time
468
*/
469
public Long getExpiresIn();
470
471
/**
472
* Get the refresh token expiration time in seconds
473
* @return Refresh expiration time
474
*/
475
public Long getRefreshExpiresIn();
476
477
/**
478
* Get the granted scope
479
* @return Space-separated scope values
480
*/
481
public String getScope();
482
483
/**
484
* Get the session state
485
* @return Session state value
486
*/
487
public String getSessionState();
488
489
/**
490
* Get error code (if response contains error)
491
* @return Error code
492
*/
493
public String getError();
494
495
/**
496
* Get error description (if response contains error)
497
* @return Error description
498
*/
499
public String getErrorDescription();
500
501
/**
502
* Get error URI (if response contains error)
503
* @return Error URI
504
*/
505
public String getErrorUri();
506
507
/**
508
* Get custom response parameter
509
* @param name Parameter name
510
* @return Parameter value
511
*/
512
public Object getOtherParam(String name);
513
}
514
515
/**
516
* OAuth2 device authorization response
517
*/
518
public class OAuth2DeviceAuthorizationResponse {
519
/**
520
* Get the device code
521
* @return Device code string
522
*/
523
public String getDeviceCode();
524
525
/**
526
* Get the user code
527
* @return User code string
528
*/
529
public String getUserCode();
530
531
/**
532
* Get the verification URI
533
* @return Verification URI
534
*/
535
public String getVerificationUri();
536
537
/**
538
* Get the complete verification URI
539
* @return Complete verification URI with user code
540
*/
541
public String getVerificationUriComplete();
542
543
/**
544
* Get the expiration time in seconds
545
* @return Expiration time
546
*/
547
public Integer getExpiresIn();
548
549
/**
550
* Get the polling interval in seconds
551
* @return Polling interval
552
*/
553
public Integer getInterval();
554
}
555
556
/**
557
* OIDC UserInfo endpoint response
558
*/
559
public class UserInfo {
560
/**
561
* Get the subject claim (sub)
562
* @return Subject identifier
563
*/
564
public String getSubject();
565
566
/**
567
* Get the preferred username
568
* @return Preferred username
569
*/
570
public String getPreferredUsername();
571
572
/**
573
* Get the email address
574
* @return Email address
575
*/
576
public String getEmail();
577
578
/**
579
* Get the email verification status
580
* @return Email verification status
581
*/
582
public Boolean getEmailVerified();
583
584
/**
585
* Get the full name
586
* @return Full name
587
*/
588
public String getName();
589
590
/**
591
* Get the given name
592
* @return Given/first name
593
*/
594
public String getGivenName();
595
596
/**
597
* Get the family name
598
* @return Family/last name
599
*/
600
public String getFamilyName();
601
602
/**
603
* Get custom UserInfo claim
604
* @param name Claim name
605
* @return Claim value
606
*/
607
public Object getClaim(String name);
608
609
/**
610
* Get all claims
611
* @return Map of all claims
612
*/
613
public Map<String, Object> getClaims();
614
}
615
```
616
617
### Claims and Address Representations
618
619
```java { .api }
620
/**
621
* OIDC address claim representation
622
*/
623
public class AddressClaimSet {
624
/**
625
* Get the formatted address
626
* @return Complete formatted address
627
*/
628
public String getFormatted();
629
630
/**
631
* Get the street address
632
* @return Street address
633
*/
634
public String getStreetAddress();
635
636
/**
637
* Get the locality (city)
638
* @return Locality/city
639
*/
640
public String getLocality();
641
642
/**
643
* Get the region (state/province)
644
* @return Region/state
645
*/
646
public String getRegion();
647
648
/**
649
* Get the postal code
650
* @return Postal/zip code
651
*/
652
public String getPostalCode();
653
654
/**
655
* Get the country
656
* @return Country name or code
657
*/
658
public String getCountry();
659
}
660
661
/**
662
* Claims request representation for OIDC
663
*/
664
public class ClaimsRepresentation {
665
/**
666
* Get ID token claims requirements
667
* @return Map of ID token claim requirements
668
*/
669
public Map<String, ClaimRequirement> getIdToken();
670
671
/**
672
* Get UserInfo claims requirements
673
* @return Map of UserInfo claim requirements
674
*/
675
public Map<String, ClaimRequirement> getUserinfo();
676
677
/**
678
* Individual claim requirement
679
*/
680
public static class ClaimRequirement {
681
/**
682
* Check if claim is essential
683
* @return true if essential
684
*/
685
public Boolean getEssential();
686
687
/**
688
* Get expected claim value
689
* @return Expected value
690
*/
691
public String getValue();
692
693
/**
694
* Get expected claim values
695
* @return Array of expected values
696
*/
697
public String[] getValues();
698
}
699
}
700
701
/**
702
* Authorization details for rich authorization requests
703
*/
704
public class AuthorizationDetailsJSONRepresentation {
705
/**
706
* Get the authorization details type
707
* @return Type identifier
708
*/
709
public String getType();
710
711
/**
712
* Get the locations
713
* @return Array of location URIs
714
*/
715
public String[] getLocations();
716
717
/**
718
* Get the actions
719
* @return Array of action identifiers
720
*/
721
public String[] getActions();
722
723
/**
724
* Get the data types
725
* @return Array of data type identifiers
726
*/
727
public String[] getDataTypes();
728
729
/**
730
* Get the identifier
731
* @return Resource identifier
732
*/
733
public String getIdentifier();
734
735
/**
736
* Get custom authorization detail parameter
737
* @param name Parameter name
738
* @return Parameter value
739
*/
740
public Object getCustomParameter(String name);
741
}
742
```
743
744
### DPoP (Demonstration of Proof-of-Possession)
745
746
```java { .api }
747
/**
748
* DPoP (Demonstration of Proof-of-Possession) token representation
749
*/
750
public class DPoP extends JsonWebToken {
751
/**
752
* Get the HTTP method (htm claim)
753
* @return HTTP method
754
*/
755
public String getHttpMethod();
756
757
/**
758
* Get the HTTP URI (htu claim)
759
* @return HTTP URI
760
*/
761
public String getHttpUri();
762
763
/**
764
* Get the access token hash (ath claim)
765
* @return Access token hash
766
*/
767
public String getAccessTokenHash();
768
769
/**
770
* Get the nonce (nonce claim)
771
* @return Nonce value
772
*/
773
public String getNonce();
774
}
775
```
776
777
## Usage Examples
778
779
```java
780
import org.keycloak.representations.*;
781
import org.keycloak.TokenVerifier;
782
783
// Working with Access Token
784
AccessToken accessToken = TokenVerifier.create(tokenString, AccessToken.class)
785
.publicKey(publicKey)
786
.verify();
787
788
// Check roles and permissions
789
String subject = accessToken.getSubject();
790
String scope = accessToken.getScope();
791
792
AccessToken.Access realmAccess = accessToken.getRealmAccess();
793
if (realmAccess != null && realmAccess.isUserInRole("admin")) {
794
// Handle admin access
795
}
796
797
AccessToken.Access clientAccess = accessToken.getResourceAccess("my-client");
798
if (clientAccess != null && clientAccess.isUserInRole("manager")) {
799
// Handle client-specific role
800
}
801
802
// Working with ID Token
803
IDToken idToken = TokenVerifier.create(idTokenString, IDToken.class)
804
.publicKey(publicKey)
805
.verify();
806
807
String email = idToken.getEmail();
808
String name = idToken.getName();
809
Boolean emailVerified = idToken.getEmailVerified();
810
811
AddressClaimSet address = idToken.getAddress();
812
if (address != null) {
813
String city = address.getLocality();
814
String country = address.getCountry();
815
}
816
817
// Working with token response
818
AccessTokenResponse response = // ... obtained from token endpoint
819
String accessTokenString = response.getToken();
820
String refreshTokenString = response.getRefreshToken();
821
String idTokenString = response.getIdToken();
822
Long expiresIn = response.getExpiresIn();
823
824
// Error handling
825
if (response.getError() != null) {
826
String error = response.getError();
827
String errorDescription = response.getErrorDescription();
828
// Handle error
829
}
830
```