Sub topic 4
Reading the claims that matter
This chapter assumes you know the three-part JWT layout from the previous chapter (header, payload, signature) and can write a basic Spring Boot controller. It covers the registered claims that a resource server reads, what each one means, and how to inspect them in Spring Security.
What a claim is
A claim is one name and value pair in the JWT payload. The payload is a JSON object, so every claim is a key in that object. The JWT specification (RFC 7519) defines a short list of registered claim names. Authorization servers add their own claims on top, such as scope, roles, or email.
A decoded payload from a typical token looks like this:
{
"iss": "https://issuer.example.com/realms/demo",
"sub": "5f2c8a1e-3b7d-4c9a-9e61-0d4f7a2b8c11",
"aud": ["orders-api"],
"exp": 1790000900,
"nbf": 1790000000,
"iat": 1790000000,
"scope": "orders.read profile"
}The signature does not hide the payload. Anyone who holds the token can base64url-decode and read these claims. The signature only guarantees that nobody changed them. Never put secrets in a JWT.
The registered claims
| Claim | Name | Meaning | Type |
|---|---|---|---|
| `iss` | Issuer | Who created the token | String, usually a URL |
| `sub` | Subject | Who the token is about | String |
| `aud` | Audience | Which services may accept the token | String or array of strings |
| `exp` | Expiration time | The moment after which the token is invalid | Seconds since the Unix epoch |
| `nbf` | Not before | The moment before which the token is invalid | Seconds since the Unix epoch |
| `iat` | Issued at | When the token was created | Seconds since the Unix epoch |
Every registered claim is optional in the JWT specification. Whether your API requires one is a policy decision. In practice, require iss, exp, and aud.
iss: who issued it
iss identifies the authorization server. A resource server must accept tokens only from issuers it trusts. If you configure issuer-uri, Spring Security compares the token's iss to that value by exact string match. A trailing slash or a different scheme makes the comparison fail.
sub: who it is about
sub identifies the principal. For a user token it is the user. For a client credentials token (a machine-to-machine token with no user), it is usually the client. Treat sub as unique only within one issuer. Two issuers can both produce sub: "42". If you store data per user, key it on the pair of iss and sub.
aud: who it is for
aud names the services that should accept the token. A token issued for billing-api should not work on orders-api, even if both trust the same issuer. The value can be a single string or an array, which is a common source of bugs. Spring's Jwt class normalizes this for you through getAudience(), which always returns a List<String>.
Spring Boot does not check aud by default. A later chapter adds an audience validator. For now, remember that without one, any token from your issuer passes this check.
exp, nbf, iat: time
These three claims are numeric dates, in seconds (not milliseconds) since 1970-01-01 UTC. Spring converts them to java.time.Instant for you.
expis the end of the token's life. The default validator rejects the token after this instant.nbfis the start. The token is rejected before this instant.iatrecords creation time. The default validator does not enforce it. Use it for logging or for your own maximum-age rules.
Spring's default timestamp validator allows 60 seconds of clock skew. A token that expired 30 seconds ago on your server's clock can still be accepted. If you see intermittent failures between servers, check that their clocks are synchronized with NTP.
Custom claims
Anything outside the registered list is a custom claim. The two you will meet most often:
scope(orscp): a space-separated string of OAuth2 scopes, for example"orders.read profile". Some providers send an array instead.rolesorgroups: an array of strings. The location and name vary by provider. Some nest them, as in Keycloak'srealm_access.roles.
Spring does nothing with roles by default. By default it reads only scope and scp. A later chapter on authority mapping shows how to change that.
Reading claims in Spring Security
After a token passes validation, Spring Security builds a JwtAuthenticationToken. Its principal is a Jwt object that gives you typed access to every claim.
| Method | Returns |
|---|---|
| `getIssuer()` | `URL` |
| `getSubject()` | `String` |
| `getAudience()` | `List<String>` |
| `getExpiresAt()` | `Instant` |
| `getNotBefore()` | `Instant` |
| `getIssuedAt()` | `Instant` |
| `getClaimAsString(name)` | `String` or `null` |
| `getClaimAsStringList(name)` | `List<String>` or `null` |
| `getClaims()` | `Map<String, Object>` |
The simplest way to reach the token is the @AuthenticationPrincipal annotation on a controller parameter:
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
class ClaimsController {
@GetMapping("/claims")
Map<String, Object> claims(@AuthenticationPrincipal Jwt jwt) {
Map<String, Object> result = new LinkedHashMap<>();
result.put("issuer", jwt.getIssuer() == null ? null : jwt.getIssuer().toString());
result.put("subject", jwt.getSubject());
result.put("audience", jwt.getAudience());
result.put("expiresAt", jwt.getExpiresAt());
result.put("secondsLeft",
jwt.getExpiresAt() == null
? null
: jwt.getExpiresAt().getEpochSecond() - Instant.now().getEpochSecond());
result.put("scope", jwt.getClaimAsString("scope"));
return result;
}
}LinkedHashMap is used because Map.of rejects null values, and optional claims may be absent. Add a null check for getIssuer() for the same reason.
Edge cases to know
- Missing claims return null.
getSubject()returnsnullwhensubis absent. Code that calls.toString()on a missing value throws aNullPointerException. audcan be a string. UsegetAudience(), notgetClaim("aud"), so you do not have to handle both shapes yourself.scopecan be a string or a list. Spring's default converter handles both. If you read the claim by hand, check the type.- Claims are untrusted until the signature is verified. Do not read a claim from a token before the decoder has validated it. Inside a controller, the
Jwthas already passed validation. Do not decode tokens yourself with a plain base64 decoder to make security decisions. issis a string in the token but aURLin the Java object. A malformed value can fail conversion. This makes the token invalid, which is the safe outcome.- Large claim sets inflate every request. The token travels in a header on each call. Many servers limit header size to around 8 KB, so keep the payload small.
How the claims flow through a request
The following sequence shows when each claim is consulted.
Notice the order. The decoder verifies the signature first and checks claims second. Only then do converters and controllers see the data.
Practical guidance
- Use
subas the stable user identifier, never an email or username claim, since those can change. - Use
isstogether withsubas a composite key if you ever accept more than one issuer. - Log
sub,iss, andexp. Do not log the whole token, because a logged token is a usable credential until it expires. - Decide which claims your API requires and write them down. A token without
audshould be rejected, not silently accepted.
Exercise
A token's payload contains "exp": 1790000900. Your service logs show that every request fails with an expired-token error, and you find that your own code converts exp with Instant.ofEpochMilli(). What is wrong, and what is the fix?
Show answer
The exp claim counts seconds since the Unix epoch, but Instant.ofEpochMilli() treats the number as milliseconds. That yields a date in January 1970, so the token looks long expired. Use Instant.ofEpochSecond(), or better, call jwt.getExpiresAt(), which Spring already converts correctly.
Exercise
Two different authorization servers both issue tokens to your API, and both contain "sub": "42". How should you identify the user in your database?
Show answer
Use the pair of iss and sub as the key. A sub value is unique only within its issuer, so sub alone could merge two different users.