Implementing OAuth 2.0 and OpenID Connect

1. Understanding OAuth 2.0 Flow Types

Flow Use Case
Authorization Code + PKCE SPAs, mobile, web apps (recommended)
Client Credentials Service-to-service (no user)
Device Code TVs, CLI
Refresh Token Get new access token
Implicit DEPRECATED Legacy SPA — use code+PKCE
Password DEPRECATED Use code flow

2. Configuring OAuth 2.0 Client

Example: OAuth2 client dependency

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

3. Registering OAuth 2.0 Providers

Example: Register Google OAuth2 provider

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: ${GOOGLE_CLIENT_ID}
            client-secret: ${GOOGLE_CLIENT_SECRET}
            scope: [openid, profile, email]
        provider:
          google:
            issuer-uri: https://accounts.google.com

4. Implementing Authorization Code Flow

Authorization Code Flow

User → /oauth2/authorization/google
   ↓
Auth Server (login + consent)
   ↓ redirect with ?code=XYZ
App ← /login/oauth2/code/google
   ↓ exchange code for tokens
Access + ID Token → session

5. Using OAuth 2.0 Login (oauth2Login())

Example: Enable OAuth2 login with redirect

@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
  return http
    .authorizeHttpRequests(a -> a.anyRequest().authenticated())
    .oauth2Login(o -> o.defaultSuccessUrl("/", true))
    .logout(l -> l.logoutSuccessUrl("/"))
    .build();
}

6. Accessing Protected Resources

Example: Access OAuth2 token and OIDC user info

@GetMapping("/me")
public Map<String,Object> me(
    @RegisteredOAuth2AuthorizedClient("google") OAuth2AuthorizedClient client,
    @AuthenticationPrincipal OidcUser user) {
  String token = client.getAccessToken().getTokenValue();
  return Map.of("name", user.getFullName(), "email", user.getEmail());
}

7. Implementing Resource Server

Example: Resource server with JWKS URI

http.oauth2ResourceServer(o -> o
  .jwt(j -> j.jwkSetUri("https://auth.example.com/.well-known/jwks.json")));
Property Description
spring.security.oauth2.resourceserver.jwt.issuer-uri Discovery
spring.security.oauth2.resourceserver.jwt.jwk-set-uri Direct JWKS
opaquetoken.introspection-uri RFC 7662 introspection

8. Validating JWT Access Tokens

Validation Performed By
Signature JwtDecoder using JWKS
exp / nbf Default validators
iss / aud Add custom OAuth2TokenValidator

9. Configuring OIDC User Info Endpoint

Element Description
OidcUser Principal containing ID token claims
OidcUserService Customize loaded user
userInfoEndpoint().userService(...) Plug custom service

10. Customizing OAuth 2.0 Success/Failure Handlers

Example: Custom OAuth2 success and failure handlers

http.oauth2Login(o -> o
  .successHandler((req,res,auth) -> res.sendRedirect("/dashboard"))
  .failureHandler((req,res,ex) -> res.sendError(401, ex.getMessage())));

11. Implementing Social Login Integration

Provider Pre-registered
Google Yes (CommonOAuth2Provider)
GitHub Yes
Facebook Yes
Okta Yes
Custom Define provider.x.* manually