Return to site

🛡️🔑 SECURE A REST API WITH SPRING SECURITY OAUTH2 RESOURCE SERVER (JWT)

· spring

🔸 TL;DR ⚡

Add spring-boot-starter-oauth2-resource-server

  1. ▪️ Set issuer-uri (or jwk-set-uri)
  2. ▪️ Protect routes + authorize with SCOPE_... (or your custom roles mapping)

🔸 WHAT “RESOURCE SERVER” MEANS (NO CONFUSION!)

Your REST API is not the login page and it doesn’t “do OAuth flows”. It simply accepts Bearer tokens (usually JWTs) issued by an Authorization Server (Keycloak, Auth0, Okta, Spring Authorization Server…) and then:

  1. ▪️ verifies the token signature (JWKs) ✅
  2. ▪️ checks expiration / issuer claims ✅
  3. ▪️ maps scopes → Spring authorities (often SCOPE_...) ✅

🔸 DEPENDENCIES (BOOT 3+/SECURITY 6+) Maven

🔸 CONFIGURE JWT VALIDATION (ISSUER OR JWK SET) application.yml

🔸 LOCK DOWN ENDPOINTS WITH SecurityFilterChain

🔸 AUTHORIZE WITH SCOPES (THE FUN PART 🔥)

Example controller using scopes as authorities:

If your provider uses a different claim (scp, roles, etc.), plug your own converter:

…and wire it:

🔸 TAKEAWAYS ✅

  1. ▪️ Resource Server = token validation, not “OAuth login”
  2. ▪️ Prefer issuer-uri when possible (cleaner + discovery-based)
  3. ▪️ Use method security (@PreAuthorize) for clear, readable authorization rules
  4. ▪️ Expect: missing token → 401, missing scope/role → 403 🔒

#SpringBoot #SpringSecurity #OAuth2 #ResourceServer #JWT #API #Java #DevSecOps #Backend #Security

Go further with Java certification:

Java👇

Spring👇

SpringBook👇

JavaBook👇