Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 66 ยท Security

JWT and OAuth 2 Resource Server

Secure a stateless Spring Boot API with JWTs: how tokens are signed and validated, scopes and roles, issuers, refresh tokens and login with an OAuth 2 provider.

The previous lesson used sessions and passwords: a user logs in, the server remembers them, and a cookie links later requests to that memory. That works well for server-rendered websites. It works less well for APIs called by mobile apps, single-page applications and other services, where keeping per-user state on the server is awkward and where you often do not want your API to handle passwords at all.

The modern answer is tokens. A client obtains a token from an authorization server and sends it with each request in an Authorization: Bearer ... header. Your API, called a resource server, only has to check that the token is genuine and has not expired. There is no session to look up. The most common token format is the JWT (JSON Web Token), and Spring Boot can validate JWTs with a few lines of configuration.

This lesson explains what is inside a JWT, how a resource server validates one, how scopes and roles become authorities, how refresh tokens fit in, and where "login with Google" belongs. For the framework view from the Spring side, see JWT Authentication and OAuth 2 Resource Server. Real Spring Security and a real authorization server do not run on this site, so that code is read-only. The runnable stand-ins sign and verify a real HMAC-signed token, map claims to authorities, and simulate refresh-token rotation.

Three roles in OAuth 2

Client The app acting for the user.
Authorization server Logs the user in and issues tokens.
Resource server Your API. It only validates tokens.

In this lesson, Spring Boot is the resource server.

1 / 2

What a JWT contains

A JWT is a string of three parts separated by dots: header.payload.signature. Header and payload are JSON documents encoded as base64url, which is encoding, not encryption: anyone holding the token can read it. Never put secrets in a payload. The signature is computed over the first two parts with a key. Change one character of the payload and the signature no longer matches.

The payload holds claims. Standard ones you will meet constantly:

Claim Meaning
iss Issuer: who created the token (the authorization server's URL)
sub Subject: who the token is about (a user id)
aud Audience: which API the token is meant for
exp Expiry time (seconds since 1970); after this the token is invalid
iat Issued-at time
scope or scp Permissions granted to the client, such as orders.read

Signatures come in two families. HS256 uses one shared secret for both signing and checking, so every party that can verify can also forge. RS256 and ES256 use a key pair: the authorization server signs with a private key, and every API verifies with the public key, which is safe to publish. That is why real systems use asymmetric signing, and why a resource server only needs a URL where the public keys are published (a JWK set), never a secret.

The first stand-in uses HS256 because the JDK supports it without extra libraries. It builds a token the same way a library does, then verifies it and shows what happens when someone tampers with it, lets it expire, or points it at the wrong API.

Java Sign and verify a JWT by hand

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.

What is real: the token format, the HMAC signature, and every one of those checks. A tampered payload fails because the signature is computed over exactly the bytes that were sent. What is the stand-in: a library such as Nimbus (used inside Spring Security) also handles asymmetric keys and key rotation through the kid header, clock skew (Spring allows 60 seconds by default), nbf, and many encoding edge cases. The alg: none test shows a classic attack: a verifier must decide which algorithm is acceptable itself, never trust the token's own header.

A Boot resource server

Add the starter:

XML
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

Tell Boot where tokens come from:

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

With issuer-uri, Boot asks the issuer's discovery document (/.well-known/openid-configuration) for the location of its public keys, downloads them, caches them and refreshes when keys rotate. Every token is then checked for a valid signature, an unexpired exp, and the right iss. If you cannot use discovery, jwk-set-uri points straight at the key set. The application starts even if the issuer is unreachable, and the first request that needs the keys fails until it is back.

Then declare the chain, built on the same SecurityFilterChain model as in Spring Security Fundamentals:

Java
@Configuration
@EnableMethodSecurity
public class ApiSecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/actuator/health").permitAll()
                .requestMatchers(HttpMethod.GET, "/orders/**").hasAuthority("SCOPE_orders.read")
                .requestMatchers(HttpMethod.POST, "/orders/**").hasAuthority("SCOPE_orders.write")
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .oauth2ResourceServer(oauth -> oauth.jwt(withDefaults()))
            .sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .csrf(csrf -> csrf.disable());
        return http.build();
    }
}

Three details deserve a note. STATELESS tells Spring never to create an HTTP session, so each request stands alone. CSRF protection is disabled only because there are no cookies to ride on: the token travels in a header the browser does not attach automatically. (If you also serve cookie-authenticated pages from the same app, keep CSRF on for them; web hardening has its own lesson.) And the 401 response for a missing or bad token carries a WWW-Authenticate: Bearer header, as the standard requires.

Inside a controller, the validated token is available as an argument:

Java
@GetMapping("/me")
Map<String, Object> me(@AuthenticationPrincipal Jwt jwt) {
    return Map.of("user", jwt.getSubject(), "scopes", jwt.getClaimAsString("scope"));
}

Scopes and roles become authorities

Spring does not know your claims. By default it turns the scope (or scp) claim into authorities with a SCOPE_ prefix: orders.read orders.write becomes SCOPE_orders.read and SCOPE_orders.write. That is why the rules above use hasAuthority("SCOPE_orders.read").

Scopes describe what the client application may do on the user's behalf ("this app may read orders"). Roles describe what the user is (ADMIN). Identity providers put roles in different claims (roles, groups, realm_access.roles in Keycloak), so you usually add a converter:

Java
@Bean
JwtAuthenticationConverter jwtAuthenticationConverter() {
    var authorities = new JwtGrantedAuthoritiesConverter();
    authorities.setAuthoritiesClaimName("roles");
    authorities.setAuthorityPrefix("ROLE_");

    var converter = new JwtAuthenticationConverter();
    converter.setJwtGrantedAuthoritiesConverter(authorities);
    return converter;
}

and register it with oauth.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())). A custom converter that merges SCOPE_ and ROLE_ authorities from both claims is also common. The second stand-in performs that mapping and then makes the same allow-or-deny decisions as the rules above.

Java From claims to access decisions

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.

What is real: the prefix convention and the two-claim mapping. What is the stand-in: Spring's converters produce GrantedAuthority objects, support nested claims and run inside the filter chain.

Validating more than the signature

A valid signature only proves the token came from someone with the key. Add checks that match your trust model:

  • Audience. Reject tokens that were issued for a different API. Spring does not check aud by default; add a validator with JwtDecoders.fromIssuerLocation(...) plus a DelegatingOAuth2TokenValidator that includes an audience check.
  • Issuer. issuer-uri already validates iss. Accept exactly the issuers you trust and no others; multi-tenant systems use a JwtIssuerAuthenticationManagerResolver with an allowlist.
  • Lifetime. Keep access tokens short (5 to 15 minutes). A JWT cannot be revoked once issued; it is valid until exp. Short lifetimes bound the damage of a leak.
  • Sensitive actions. For high-risk operations, check something stronger than the token alone, such as a fresh login or a lookup of the account's status.

Refresh tokens and sessions

Short-lived access tokens would force users to log in every quarter of an hour, so the authorization server also issues a refresh token: a long-lived credential the client keeps safely and exchanges for new access tokens. This exchange is between the client and the authorization server only. Your resource server never sees refresh tokens and never issues tokens itself.

Good authorization servers use refresh token rotation: every refresh returns a new refresh token and invalidates the old one. If an old token is ever presented again, someone stole it, and the server revokes the whole chain so the thief and the real user are both forced to log in again. The last stand-in simulates exactly that.

Java Refresh token rotation and reuse detection

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.

What is real: the rotation and reuse-detection idea (it is in the OAuth 2 security best practices). What is the stand-in: real servers (Keycloak, Auth0, Spring Authorization Server) sign tokens, bind them to a client, expire them and persist state in a database.

Where do clients keep tokens? Browser apps face a trade-off: localStorage is readable by any injected script (XSS), while an HttpOnly cookie is not, but brings CSRF back into play. Many teams therefore put a small backend in front of the single-page app (the "backend for frontend" pattern) that holds the tokens and gives the browser an ordinary session cookie.

Login with OAuth 2 (the client side)

Everything above protects an API. The other common need is "Sign in with Google (or GitHub, or your company account)" for a website. Here Spring Boot is the OAuth 2 client: it sends the user to the provider, receives an authorization code, exchanges it for tokens and creates a normal login session.

XML
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
YAML
spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: ${GOOGLE_CLIENT_ID}
            client-secret: ${GOOGLE_CLIENT_SECRET}
            scope: openid,profile,email
Java
http
    .authorizeHttpRequests(auth -> auth
        .requestMatchers("/", "/error").permitAll()
        .anyRequest().authenticated())
    .oauth2Login(withDefaults());

Boot knows Google's endpoints from the registration name, so only the id, secret and scopes are yours, and the secret comes from the environment, never from a committed file. The openid scope turns it into OpenID Connect (OIDC), which adds an ID token describing the user. You can combine both sides in one application: oauth2Login for the human-facing pages and oauth2ResourceServer for /api/**, each in its own SecurityFilterChain.

Choosing an approach

  • Server-rendered site, one application: sessions and form login are simpler and revocable.
  • API for your own SPA or mobile app: an authorization server (Keycloak, Auth0, Okta, Spring Authorization Server) plus a resource server as shown.
  • Service-to-service calls: the OAuth 2 client credentials grant with a short-lived JWT.
  • Do not write your own login, token format or password reset if a provider can do it. Building an authorization server yourself is a long project.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Is the payload of a JWT encrypted?

    A normal signed JWT provides integrity, not secrecy. Do not put secrets in claims.
  2. 2. Why do real systems prefer RS256 over HS256 for tokens read by many APIs?

    With HS256 every verifier shares the signing secret and could mint tokens. With a key pair, only the authorization server holds the private key.
  3. 3. A token has the claim scope: "orders.read". Which authority does Spring Security grant by default?

    The default converter prefixes each scope with SCOPE_, so rules use hasAuthority("SCOPE_orders.read").
  4. 4. What is the main reason to keep access tokens short-lived?

    The resource server only checks signature and expiry. Short lifetimes plus refresh tokens balance safety and convenience.
  5. 5. Who handles refresh tokens in a typical setup?

    The client exchanges the refresh token with the authorization server. The resource server only ever sees access tokens.

Summary

  • A JWT is header.payload.signature: readable, but tamper-evident through its signature; claims such as iss, sub, aud, exp and scope describe it.
  • A Boot resource server needs the oauth2 resource server starter and an issuer-uri; it then checks signature, expiry and issuer for every request, statelessly.
  • Scopes become SCOPE_ authorities by default; map role claims with a JwtAuthenticationConverter, and validate the audience yourself.
  • Keep access tokens short, rotate refresh tokens at the authorization server, and let the resource server never touch them.
  • oauth2Login with the client starter gives "sign in with a provider" for websites.

Next: CSRF, CORS and Secure Defaults.