How does Spring Security integrate with OAuth2 for authorization?

Spring Security integrates with OAuth2 by acting as an OAuth2 client (or resource server) that delegates authentication to an external authorization server and uses the resulting access token to authorize requests. Rather than managing credentials itself, the application trusts tokens issued by a provider such as Okta, Google, or Keycloak.

Key Points: • spring-boot-starter-oauth2-client handles the authorization code flow and token exchange automatically. • spring-boot-starter-oauth2-resource-server validates incoming bearer tokens (JWT or opaque) on protected APIs. • The authorization server issues, signs, and can revoke tokens, keeping credential handling out of the application. • Scopes and claims in the token map to granted authorities used in access-control decisions. • Token validation typically checks signature, issuer, audience, and expiration.

Example: A user hits a protected page, Spring Security redirects to the OAuth2 provider's login screen, and after login the provider returns an authorization code that the app exchanges for an access token, e.g. via oauth2Login() configuration.

Interview Tip: A concise interview answer is:

"Spring Security integrates with OAuth2 by delegating authentication to an external authorization server, which issues access tokens after the user logs in. Spring Security then validates and uses those tokens to authorize access, using starters like oauth2-client for login flows and oauth2-resource-server for validating bearer tokens on APIs."