Video in progress

Senior 🌱 Spring

How does a microservice check tokens as an OAuth2 resource server, and what decisions do you make along the way?

The service verifies the JWT signature itself with the authorization server's public keys (JWKS), checks the iss, exp and aud claims, and turns scopes/roles into authorities. The decisions: JWT or opaque token, token lifetime, audience, and how to revoke.

📖 Answer

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://sso.company.uz/realms/main
          audiences: orders-api

Spring finds the JWKS address from issuer-uri on its own, caches the keys and refreshes them when the kid changes.

Roles:

@Bean
JwtAuthenticationConverter jwtAuth() {
    var roles = new JwtGrantedAuthoritiesConverter();
    roles.setAuthoritiesClaimName("roles");
    roles.setAuthorityPrefix("ROLE_");
    var c = new JwtAuthenticationConverter();
    c.setJwtGrantedAuthoritiesConverter(roles);
    return c;
}

The decisions:

  • A JWT is verified without a network call, so it's fast. An opaque token needs introspection every time, but it can be revoked instantly. Often people pick the middle: a short-lived JWT (5-10 minutes).
  • If aud isn't checked, a token issued for another service will also pass on yours. People often forget this in interviews.
  • For service-to-service calls you either pass the user's token along (token relay) or get a service token with client credentials, depending on whose behalf the work is done on.
  • A blocked user keeps working until the token expires. For critical operations like money or passwords, you need an extra check or a revocation list.
  • with issuer-uri Spring contacts the SSO not at startup but on the first JWT: the service comes up, but if the SSO is down the first requests fail. jwk-set-uri removes the discovery step.