Skip to content
Tutorials Center
My learning

Topics

Lesson 80 of 119 ยท Spring Boot

JWT and OAuth 2

Learn how JSON Web Tokens work by building and verifying HS256 and RS256 tokens in plain Java, then secure Spring Boot APIs with OAuth 2 and OpenID Connect.

A REST API that serves mobile apps, single-page apps and other services usually can't rely on a server-side session. Instead, every request carries a token that proves who the caller is and what they may do. The most common token format is the JSON Web Token (JWT), and the most common way to obtain one is OAuth 2 with OpenID Connect.

Both topics are surrounded by jargon and by libraries that hide the details. In this lesson you will build and verify real JWTs with nothing but the JDK (javax.crypto, java.security and Base64), so you see exactly what a signature protects and what it doesn't. Then you will learn the OAuth 2 flows that hand out tokens, and how a Spring Boot application becomes a resource server that accepts them. You should know the basics from Web Security Basics and Spring Security.

The hand-written JWT code here is for learning. In production, use a maintained library (Spring Security's NimbusJwtDecoder, Nimbus JOSE + JWT, jjwt or Auth0 java-jwt). Token validation has many sharp edges, and a library has already been attacked and fixed many times.

Sessions versus tokens

With a session, the server stores the login state and gives the browser a random session id in a cookie. Each request sends the cookie, and the server looks up the session. This works well for classic web apps, but every server instance must reach the same session store.

With a self-contained token, the server that issues the token signs a statement such as "this is user 42, they have the scope books.read, valid until 10:15". Any service that knows the verification key can check the signature and trust the statement without a database lookup. That makes tokens a natural fit for APIs and microservices.

The price: a signed token stays valid until it expires, even if the user logs out or is banned. You will see how systems manage that trade-off later in this lesson.

Anatomy of a JWT

A JWT (RFC 7519) is three Base64URL-encoded parts joined by dots:

TEXT
header.payload.signature
  • The header is JSON describing the token, mainly the signing algorithm: {"alg":"HS256","typ":"JWT"}.
  • The payload is JSON with claims, statements about the subject.
  • The signature is computed over the exact text header.payload.

Base64URL is Base64 with - and _ instead of + and /, and without = padding, so tokens are safe in URLs and HTTP headers. It is an encoding, not encryption: anyone holding a token can read its payload. Decode one yourself:

Java Decode a JWT without any library

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

You didn't need any key to read the claims. So never put secrets in a JWT payload: no passwords, no personal data the client shouldn't see. (A different format, JWE, encrypts the payload, but most APIs use signed JWTs, called JWS.)

Registered claims

The JWT standard defines short names for common claims. All times are NumericDate: seconds (not milliseconds) since the Unix epoch.

Claim Meaning Example
iss Issuer: who created the token https://auth.example.com
sub Subject: who the token is about, usually a stable user id user-42
aud Audience: which API(s) the token is meant for (string or array) library-api
exp Expiration time; reject the token at or after it 1792499300
nbf Not before; reject the token before it 1792498400
iat Issued at 1792498400
jti Unique token id, useful for revocation lists 3f2a...

Anything else is a private claim. OAuth 2 access tokens commonly carry scope (space-separated permissions) and often custom claims such as roles.

Signing and verifying with HMAC-SHA256

HS256 means "HMAC with SHA-256". HMAC mixes a secret key into the hash, so only someone who knows the key can produce a valid signature. The verifier recomputes the HMAC over header.payload and compares it with the signature in the token.

Two details matter in the code below. First, the claim map is a LinkedHashMap and the header is a record, so the JSON field order (and therefore the token) is the same on every run. Second, the comparison uses MessageDigest.isEqual, which takes the same time whether the first byte or the last byte differs. A normal Arrays.equals can return early, and in theory an attacker could measure that to guess a signature byte by byte.

Java Build and verify an HS256 token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The token printed first is exactly the one you decoded in the previous example. Changing a single character of the header or payload changes the HMAC completely, so the forged token fails. That is the whole guarantee of a signature: integrity and authenticity, not secrecy.

For HS256, use a key of at least 256 bits (32 bytes) generated by a secure random source, for example new SecureRandom().nextBytes(key) once, then stored in your secret manager. A short human-chosen string can be brute-forced offline, because every token is a known plaintext with its HMAC.

Validating a token properly

A correct signature only proves the token was issued by someone holding the key. Before you trust it, a resource server must also check:

  1. The algorithm is the one you expect. Never let the token's header choose. The infamous "alg": "none" attack sends an unsigned token and hopes the verifier accepts it. Another attack, algorithm confusion, sends HS256 to a server that expects RS256 and signs with the server's public key as the HMAC secret.
  2. exp and nbf against the current time, with a small leeway (30 to 60 seconds) for clock differences between servers.
  3. iss equals your trusted issuer.
  4. aud contains your API. Without this check, a token issued for a different API of the same company would work on yours.
  5. Your own rules, such as required scopes.

The validator below does all of this and reports the reason for each rejection. It takes a Clock parameter, so the test cases can pretend it is a particular moment; that is the same trick you used in Test Doubles and Mockito.

Java A strict JWT validator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that the "expired" token's exp is 100 seconds in the past, beyond the 30-second leeway, and that the aud array is handled as well as a single string. Real libraries do the same checks; your job is to configure them with the right issuer, audience and algorithm, and never to turn the checks off.

Asymmetric signatures: RS256 and ES256

With HS256, the same secret signs and verifies. Every service that verifies tokens could also mint them, so a leak anywhere is a leak everywhere. That is fine when one application issues and checks its own tokens, but not for a central login server with dozens of APIs.

Asymmetric algorithms fix this. The authorization server keeps a private key and signs with it; APIs only get the public key, which can verify but never sign.

  • RS256: RSA signature with SHA-256 (SHA256withRSA in Java). Keys of 2048 bits or more; signatures are 256 bytes.
  • ES256: ECDSA on the P-256 curve with SHA-256. Much smaller keys and signatures (64 bytes). In Java use SHA256withECDSAinP1363Format, because JWT expects the raw r || s signature format rather than the DER format that plain SHA256withECDSA produces.

Authorization servers publish their public keys as a JWK Set at a URL such as https://auth.example.com/.well-known/jwks.json. Each key has a kid (key id), and each token's header names the kid that signed it. That makes key rotation painless: the server publishes a new key next to the old one, starts signing with it, and removes the old key after the last tokens signed with it have expired.

Java RS256: sign with the private key, verify with the public key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The key pair is random on every run, so the modulus differs each time, but the signature is always 256 bytes for a 2048-bit key. (A JWK encodes the modulus as unsigned bytes; the leading zero byte from toByteArray() is only removed in real JWK code.)

Protecting an API with bearer tokens

Clients send a token in the Authorization header using the Bearer scheme:

HTTP
GET /api/books HTTP/1.1
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ...

"Bearer" means whoever holds the token can use it, like cash. That is why tokens must only travel over HTTPS and should be short-lived. The status codes follow RFC 6750:

  • 401 Unauthorized when the token is missing, malformed, expired or badly signed. The response includes a WWW-Authenticate: Bearer header, with error="invalid_token" when a token was sent but rejected.
  • 403 Forbidden when the token is valid but lacks the required scope (error="insufficient_scope").

Here is a small API on the JDK HttpServer (as in Building a REST API with the JDK) that applies these rules, with an HttpClient playing three different callers:

Java A bearer-token protected HttpServer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This is exactly the job Spring Security's BearerTokenAuthenticationFilter does for you, with the full validation from the previous section and properly formatted error headers.

Access tokens, refresh tokens and logout

Because a JWT can't be "un-signed", systems combine several tools:

  • Short-lived access tokens. Five to fifteen minutes is common. A stolen token is useful only briefly.
  • Refresh tokens. A long-lived, usually opaque (random) token that the client sends to the authorization server to get a new access token. The server stores refresh tokens, so it can revoke them at logout. Good servers rotate refresh tokens: each use returns a new one and invalidates the old, and reuse of an old one signals theft.
  • Deny lists for emergencies. An API can reject specific jti values or all tokens of a user issued before a certain time. This adds a lookup, so keep it small and cached.
  • Opaque tokens with introspection. Instead of a JWT, the API receives a random string and asks the authorization server about it (RFC 7662 token introspection). Revocation is instant, at the cost of a network call per request (usually cached briefly).

Where should a browser app keep tokens? localStorage is readable by any script on the page, so a single XSS bug leaks every token. Safer designs keep tokens in memory only, or use the Backend for Frontend pattern: a small server-side component performs the OAuth flow, keeps the tokens, and gives the browser an HttpOnly, Secure, SameSite session cookie, as covered in Sessions and Cookies.

OAuth 2 and OpenID Connect

So far a token simply appeared. OAuth 2 (RFC 6749) is the framework that defines how a client obtains one. It names four roles:

  • Resource owner: the user.
  • Client: the application that wants to call an API on the user's behalf (a web app, mobile app, CLI).
  • Authorization server: issues tokens after authenticating the user, for example Keycloak, Okta, Auth0, Microsoft Entra ID, Google, or Spring Authorization Server.
  • Resource server: the API that accepts tokens. Your Spring Boot service.

OAuth 2 is about authorization (delegated access). OpenID Connect (OIDC) is a thin identity layer on top that adds authentication: when the client requests the openid scope, it also receives an ID token, a JWT about the user meant for the client. The access token is meant for the API. Don't send ID tokens to APIs, and don't use access tokens to learn who logged in.

Authorization Code flow with PKCE

This is the flow for any app with a user: web apps, single-page apps, mobile and desktop apps.

TEXT
 Browser / App                  Authorization server                  API
      |  1. redirect to /authorize?response_type=code
      |     &client_id=...&redirect_uri=...&scope=openid books.read
      |     &state=...&code_challenge=...&code_challenge_method=S256
      |------------------------------>|
      |  2. user logs in and consents |
      |<------------------------------|  3. redirect back with ?code=...&state=...
      |  4. POST /token: code + code_verifier (+ client secret if confidential)
      |------------------------------>|
      |<------------------------------|  5. access token (+ refresh token, ID token)
      |  6. GET /api/books  Authorization: Bearer <access token>
      |------------------------------------------------------------------->|
  • state is a random value the client checks on return, which blocks cross-site request forgery on the callback.
  • PKCE (Proof Key for Code Exchange, RFC 7636) protects the code itself. The client invents a random code_verifier, sends only its SHA-256 hash (code_challenge) in step 1, and reveals the verifier in step 4. Someone who intercepts the code can't redeem it without the verifier. OAuth 2.1 and current best practice require PKCE for all clients.

PKCE is simple enough to compute by hand:

Java Generate a PKCE verifier and challenge

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Other grant types

  • Client Credentials: no user at all. A backend service authenticates with its own id and secret (or a certificate) and gets a token to call another service. This is the standard flow between microservices.
  • Device Authorization: for TVs and CLIs without a convenient browser; the user enters a short code on another device.
  • Refresh Token: exchanging a refresh token for a new access token, described above.
  • The old Implicit and Resource Owner Password grants are deprecated. Don't use them in new code.

Spring Boot as a resource server

With Spring Security, accepting JWTs takes a dependency and two properties. Add the resource-server starter (spring-boot-starter-security-oauth2-resource-server in Boot 4; Boot 3 calls it spring-boot-starter-oauth2-resource-server, a name Boot 4 still accepts but deprecates) and configure the issuer:

YAML
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://auth.example.com/realms/library
          audiences: library-api

At startup, Spring reads issuer-uri/.well-known/openid-configuration to discover the JWK Set URL, then downloads and caches the public keys (refreshing them when an unknown kid appears). Every request's token is checked for signature, exp/nbf with 60 seconds of leeway, iss, and the configured audience: the same steps as your validator.

The security configuration turns scopes into rules. By default, each entry of the scope (or scp) claim becomes an authority named SCOPE_<scope>:

Java
@Configuration
@EnableMethodSecurity
class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/actuator/health").permitAll()
                .requestMatchers(HttpMethod.GET, "/api/books/**").hasAuthority("SCOPE_books.read")
                .requestMatchers("/api/books/**").hasAuthority("SCOPE_books.write")
                .anyRequest().authenticated())
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .csrf(csrf -> csrf.disable());   // no cookies are used, so CSRF does not apply
        return http.build();
    }
}

Controllers can read the validated token directly, and method security works with the same authorities:

Java
@RestController
@RequestMapping("/api/books")
class BookController {

    @GetMapping("/mine")
    List<BookDto> myBooks(@AuthenticationPrincipal Jwt jwt) {
        return loans.booksBorrowedBy(jwt.getSubject());
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('SCOPE_books.write') and hasRole('LIBRARIAN')")
    ResponseEntity<Void> delete(@PathVariable long id) { ... }
}

hasRole('LIBRARIAN') expects an authority named ROLE_LIBRARIAN. Authorization servers put roles in different claims (Keycloak uses realm_access.roles, others a roles claim), so you map them yourself with a JwtAuthenticationConverter bean that reads the claim and returns the matching authorities.

The other sides of OAuth 2 are just as declarative: spring-boot-starter-security-oauth2-client (spring-boot-starter-oauth2-client in Boot 3) plus http.oauth2Login(...) makes a server-side web app perform the Authorization Code flow, and OAuth2AuthorizedClientManager fetches Client Credentials tokens for service-to-service calls. If you need your own authorization server, Spring Authorization Server (part of the Spring Security project) implements one; many teams use Keycloak or a hosted provider instead.

For tests, spring-security-test lets you skip real tokens entirely: mockMvc.perform(get("/api/books").with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_books.read")))). Testing Spring Boot Applications shows the full setup.

Common mistakes

  • Trusting the payload without verifying the signature, for example decoding the token in a gateway and forwarding the claims.
  • Letting the token pick the algorithm, or accepting none.
  • Skipping the audience check, so tokens for other APIs work on yours.
  • Long-lived access tokens (days or weeks) with no revocation strategy.
  • Secrets or personal data in the payload, which anyone can read.
  • Tokens in URLs: they end up in logs, browser history and Referer headers. Use the Authorization header.
  • Weak HS256 secrets checked into Git. Use a secret manager, and prefer asymmetric keys when more than one service verifies tokens.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Someone captures a signed JWT (JWS) from your API's logs. What can they do without the key?

    Base64URL is only an encoding, so the payload is readable. A bearer token works for whoever holds it until exp. Changing any byte breaks the signature, and creating new tokens requires the key.
  2. 2. A token arrives with header {"alg":"none"} and an empty signature. What should a correct validator do?

    The validator in the lesson rejects anything that isn't the configured algorithm. Letting the header choose enables the alg none and algorithm-confusion attacks.
  3. 3. Your company runs 30 APIs that all verify tokens from one login server. Why is RS256 or ES256 a better choice than HS256?

    With HMAC, every verifier holds the signing secret. Asymmetric keys keep signing power on the authorization server alone. RS256 tokens are actually larger.
  4. 4. A request has a valid, unexpired token with scope books.read, and calls POST /api/books, which needs books.write. Which response fits RFC 6750?

    The caller is authenticated (the token is fine) but not allowed to do this, so it's 403. 401 means the credentials are missing or invalid.
  5. 5. What problem does PKCE solve in the Authorization Code flow?

    Only the hash of the verifier travels in the first redirect. The token endpoint requires the verifier itself, which never left the client.

Summary

  • A JWT is header.payload.signature in Base64URL. The payload is readable by anyone; the signature only guarantees integrity and origin.
  • Registered claims: iss, sub, aud, exp, nbf, iat, jti; times are seconds since the epoch. Access tokens usually add scope.
  • HS256 signs with a shared secret (HMAC-SHA256); RS256/ES256 sign with a private key and verify with a public key published as a JWK Set, with kid for rotation.
  • Validate everything: the expected algorithm, signature (constant-time compare), exp/nbf with small leeway, iss, aud, then scopes.
  • Send tokens as Authorization: Bearer; answer 401 for missing or bad tokens and 403 for insufficient scope.
  • Keep access tokens short-lived; use rotating refresh tokens, and keep tokens out of localStorage and URLs.
  • OAuth 2 defines how clients get tokens: Authorization Code with PKCE for users, Client Credentials for services. OpenID Connect adds the ID token for login.
  • In Spring Boot, the resource-server starter plus issuer-uri and oauth2ResourceServer(jwt) does the full validation; scopes become SCOPE_ authorities.

Next: Actuator, Metrics and Observability shows how to see what your secured service is doing in production: health checks, metrics, traces and logs.