OAuth2 and resource servers
What you will learn
OAuth2 delegates access; OpenID Connect adds identity. A resource server must verify access tokens and then enforce its own access policy.
- Distinguish OAuth2 clients, authorization servers and resource servers.
- Explain signature, issuer, audience and temporal checks.
- Interpret mock authentication tests without claiming cryptographic verification.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Spring Security examples require the separate pinned companion Maven project. Their predicted results are not execution evidence.
Already-verified claim policy model
public class Main { static boolean accept(String issuer,String audience,java.time.Instant exp,java.time.Instant now){return "issuer".equals(issuer)&&"tenant-api".equals(audience)&&exp!=null&&exp.isAfter(now);} public static void main(String[] args) {var now=java.time.Instant.parse("2026-01-01T00:00:00Z");System.out.println(accept("issuer","tenant-api",now.plusSeconds(60),now));System.out.println(accept("other","tenant-api",now.plusSeconds(60),now));System.out.println(accept("issuer","other-api",now.plusSeconds(60),now));System.out.println(accept("issuer","tenant-api",now,now)); }}Expected output:
truefalsefalsefalseA strict zero-skew model for selected claims after an assumed signature check; not a JWT decoder. Real aud may be a list and nbf must also be checked.
Roles and trust
OAuth2 lets a client obtain access to a protected resource under an authorization server’s rules; OIDC adds authentication and identity information, including an ID token. A client commonly uses authorization code with PKCE and follows redirect URI and state requirements; OIDC uses nonce as applicable. ID tokens describe an authentication event for the client; do not substitute them for API access tokens. A resource server accepts bearer access tokens, which may be opaque (introspection) or JWTs (local verification). JWT is a format, not proof of validity; signed JWT payloads are not encrypted. Tokens are sensitive and require TLS. The lab accepts a single fictional issuer; it has no live identity provider, tokens or accounts. Do not build your own token parser or verifier.
JWT verification versus authorization
Configure the trusted issuer, expected audience and JWK source independently of the token. Verify signature with trusted keys and allowed algorithms; validate iss, aud, exp and nbf with bounded clock skew as configured. Require expiration and other mandatory claims explicitly if the chosen defaults allow absence. Reject unknown issuer, wrong audience, bad signature and invalid time before deriving authorities. Key rotation and issuer availability require operational review. Boot properties configure issuer, jwk-set-uri and audiences; explicitly configuring both issuer and key URI avoids discovery but still requires trusted keys when decoding. Scope claims commonly become SCOPE_ authorities; a valid token still needs object authorization. Browser logout is not revocation of bearer access tokens. The test uses jwt() to insert synthetic identity and mocks decoder failure; neither proves actual signature or claim validation. A separate approved mock issuer and generated keys are required for end-to-end validation.
Scope after validation
public class Main {
public static void main(String[] args) {var scopes=java.util.Set.of("report.read");System.out.println(scopes.contains("report.read"));System.out.println(scopes.contains("report.write"));System.out.println(scopes.contains("admin")); }}Expected output:
truefalsefalseAccess tokens grant specific permissions; no implicit write or admin rights follow from read scope.
Issuer, audience and key configuration
Source-reviewed, NOT RUN. File lab-fixtures/spring-security-v41/src/main/resources/application.properties; use the companion lab README.
server.address=127.0.0.1spring.security.oauth2.resourceserver.jwt.issuer-uri=https://issuer.example.invalidspring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://issuer.example.invalid/keysspring.security.oauth2.resourceserver.jwt.audiences[0]=tenant-apilab.browser-password=${LAB_BROWSER_PASSWORD}Predicted behavior: Boot configures a decoder for the expected issuer and audience using trusted keys at the configured URI.
Reserved invalid domains deliberately prevent a live identity connection; real signature testing is not performed.
Resource server access tests
Source-reviewed, NOT RUN. File lab-fixtures/spring-security-v41/src/test/java/example/tenant/ApiSecurityTest.java; use the companion lab README.
package example.tenant;import org.junit.jupiter.api.*;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.bean.override.mockito.MockitoBean;import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.security.oauth2.jwt.BadJwtException;import org.springframework.security.oauth2.jwt.JwtDecoder;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.setup.MockMvcBuilders;import org.springframework.web.context.WebApplicationContext;import static org.mockito.Mockito.when;import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;@SpringBootTest(properties="lab.browser-password=synthetic-test-only")class ApiSecurityTest { @Autowired WebApplicationContext context; @MockitoBean JwtDecoder decoder; MockMvc mvc; @BeforeEach void setup() { mvc=MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); } @Test void anonymousDenied() throws Exception { mvc.perform(get("/api/tenants/north/report")).andExpect(status().isUnauthorized()); } @Test void invalidBearerDenied() throws Exception { when(decoder.decode("invalid-fixture")).thenThrow(new BadJwtException("fixture rejected")); mvc.perform(get("/api/tenants/north/report").header("Authorization","Bearer invalid-fixture")) .andExpect(status().isUnauthorized()); } @Test void missingScopeDenied() throws Exception { mvc.perform(get("/api/tenants/north/report").with(jwt().jwt(j->j.subject("alice")) .authorities(new SimpleGrantedAuthority("SCOPE_other")))).andExpect(status().isForbidden()); } @Test void crossTenantDenied() throws Exception { mvc.perform(get("/api/tenants/south/report").with(jwt().jwt(j->j.subject("alice")) .authorities(new SimpleGrantedAuthority("SCOPE_report.read")))).andExpect(status().isForbidden()); } @Test void permittedTenant() throws Exception { mvc.perform(get("/api/tenants/north/report").with(jwt().jwt(j->j.subject("alice")) .authorities(new SimpleGrantedAuthority("SCOPE_report.read")))) .andExpect(status().isOk()).andExpect(content().string("report for north")); } @Test void corsPreflight() throws Exception { mvc.perform(options("/api/tenants/north/report").header("Origin","https://ui.example.invalid") .header("Access-Control-Request-Method","GET").header("Access-Control-Request-Headers","Authorization")) .andExpect(status().isOk()).andExpect(header().string("Access-Control-Allow-Origin","https://ui.example.invalid")); mvc.perform(options("/api/tenants/north/report").header("Origin","https://other.example.invalid") .header("Access-Control-Request-Method","GET")).andExpect(status().isForbidden()); }}Predicted behavior: Anonymous and stub-invalid requests receive 401; missing scope or cross-tenant access receives 403; matching subject and scope receives 200.
jwt() bypasses decoder validation; mock CORS tests exercise preflight policy, not a real browser.
Common mistakes
Do not decode a JWT and trust claims without verification, accept arbitrary algorithms or key URLs from token headers, confuse ID tokens with API access tokens, or claim MockMvc jwt() validates signatures.
Practice
Given a synthetic fixed clock and assumed verified signature, check expected issuer, audience, non-null expiration strictly after now, and not-before no later than now. Print true for a valid set and false for expired, future nbf and wrong audience.
Expected output:
truefalsefalsefalseCompare with the manual review criteria.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
OAuth2 and resource servers — knowledge check
Spring Security identity and authorization reasoning.
What does OIDC add to OAuth2?
Which token should an API receive?
What is required before trusting JWT claims?
Does MockMvc jwt() prove the token signature is valid?
What happens when a valid scoped token targets another tenant?