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

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.

# application.yml: log in with GitHub (spring-boot-starter-oauth2-client)
spring:
  security:
    oauth2:
      client:
        registration:
          github:
            client-id: ${GITHUB_CLIENT_ID}
            client-secret: ${GITHUB_CLIENT_SECRET}
            scope: read:user

@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
    return http
            .authorizeHttpRequests(a -> a
                    .requestMatchers("/", "/public/**").permitAll()
                    .anyRequest().authenticated())
            .oauth2Login(Customizer.withDefaults())   // redirect to GitHub, handle the code
            .build();
}

// The logged-in user's details
@GetMapping("/me")
public Map<String, Object> me(@AuthenticationPrincipal OAuth2User user) {
    return Map.of("name", user.getAttribute("login"));
}

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.

Last updated: 1 November 2026

Next question: Explain Cross-Origin Resource Sharing (CORS) and how you would configure it in a Spring Boot application.

More Spring Security - Level I interview questions

All Spring Security - Level I questions