Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 39 ยท JWT and OAuth2 Resource Server

OAuth2 Resource Server Configuration

Configure a Spring Security JWT resource server: oauth2ResourceServer, JwtDecoder, issuer and audience validation, scopes to authorities, and 401 versus 403.

A resource server is an API that accepts access tokens instead of logins. It never shows a login page and never creates a session: every request carries Authorization: Bearer <token>, the server validates the token, and the request is allowed or refused. Spring Security supports this with a few lines of configuration plus the spring-boot-starter-oauth2-resource-server dependency.

The Spring libraries cannot run on this site, so the framework code below is read-only. The runnable programs are plain Java stand-ins that mimic the pipeline: bearer filter, authorities converter, authorization rules.

The minimal configuration

With Boot, setting one property is enough for a server that trusts an authorization server:

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

At start-up Boot reads the issuer's discovery document, finds its JWK Set URI, and creates a JwtDecoder that verifies signatures, exp, nbf and the iss claim. The security filter chain then looks like this:

Java
@Configuration
@EnableWebSecurity
class ApiSecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .requestMatchers(HttpMethod.GET, "/api/**").hasAuthority("SCOPE_read")
                .anyRequest().authenticated())
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .csrf(csrf -> csrf.disable());
        return http.build();
    }
}

Why csrf.disable() and STATELESS are safe here: there is no cookie that a browser sends automatically, so a forged cross-site request cannot carry credentials. If you ever add a cookie-based login, turn CSRF protection back on (see CSRF protection).

What the filter does

A bearer request

Request Authorization: Bearer ...
BearerTokenAuthenticationFilter Extracts the token
JwtDecoder Verifies and parses

Invalid token: 401 Unauthorized

1 / 2

The result of a successful decode is a JwtAuthenticationToken. Its authorities come from a JwtAuthenticationConverter.

Scopes and authorities

By default Spring reads the scope (or scp) claim, splits it on spaces and prefixes each value with SCOPE_. A token with "scope": "read write" therefore grants SCOPE_read and SCOPE_write, checked with hasAuthority("SCOPE_read"). If your tokens carry roles in a custom claim, change the converter:

Java
@Bean
JwtAuthenticationConverter jwtAuthenticationConverter() {
    JwtGrantedAuthoritiesConverter authorities = new JwtGrantedAuthoritiesConverter();
    authorities.setAuthoritiesClaimName("roles");   // read this claim instead of scope
    authorities.setAuthorityPrefix("ROLE_");        // so hasRole("ADMIN") works

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

and register it with oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())).

The next program is a stand-in for the converter. It takes a claims map and produces the authority list in the same way, so you can try the naming rules.

Java Claims to authorities (stand-in)

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.

Audience and custom validation

Checking the issuer is not enough when one authorization server issues tokens for many APIs. A token meant for billing-api must be rejected by orders-api. Add an audience validator:

Java
@Bean
JwtDecoder jwtDecoder() {
    NimbusJwtDecoder decoder = JwtDecoders.fromIssuerLocation("https://auth.example.com");
    OAuth2TokenValidator<Jwt> audience = new JwtClaimValidator<List<String>>(
        "aud", aud -> aud != null && aud.contains("orders-api"));
    OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer("https://auth.example.com");
    decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(withIssuer, audience));
    return decoder;
}

401 versus 403

This distinction is a common interview question and a common bug:

Status Meaning Spring component
401 Unauthorized Missing or invalid credentials (no token, bad signature, expired) BearerTokenAuthenticationEntryPoint, adds WWW-Authenticate: Bearer
403 Forbidden Authenticated, but not allowed BearerTokenAccessDeniedHandler

The stand-in below runs a request through the same decisions: extract the bearer token, validate it, convert the claims, apply the rules.

Java Bearer pipeline: 401 versus 403 (stand-in)

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.

Read the table of results carefully: the same user (tok-alice) gets 200 on a read, 403 on a write, and 403 on the admin path. A 401 only appears when the token itself is missing or wrong.

Opaque tokens as an alternative

If the authorization server issues random strings instead of JWTs, use oauth2.opaqueToken(...) and an introspection endpoint. Every request then costs one network call (usually cached) but you gain instant revocation. Spring Security gives both models the same Authentication abstraction, so your authorization rules stay the same.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A request carries a valid token but lacks the required scope. What status should the API return?

    The caller is authenticated but not authorized. 401 is for missing or invalid credentials.
  2. 2. By default, which prefix does Spring add to values of the scope claim?

    JwtGrantedAuthoritiesConverter maps scope read to the authority SCOPE_read.
  3. 3. Why does a JWT resource server usually disable CSRF and use stateless sessions?

    CSRF abuses cookies the browser sends on its own. A bearer header must be set by the client's code.
  4. 4. What problem does an audience (aud) validator solve?

    The issuer check only proves who made the token. The audience check proves it was meant for this resource server.

Summary

  • A resource server accepts bearer tokens and keeps no session.
  • One issuer-uri property gives you signature, expiry and issuer validation.
  • JwtAuthenticationConverter turns claims into authorities; the default prefix is SCOPE_.
  • Add audience validation when an issuer serves several APIs.
  • 401 means "who are you?", 403 means "you may not do that".

Next: Refresh tokens and revocation