Spring Security OAuth2 login uses an authorization-code redirect to authenticate a browser user and establish a local authenticated session. The identity provider supplies an identity assertion; the application still decides which local account and permissions that identity receives.
Spring Security OAuth2 login: callback, identity and browser session
Trace the redirect boundary
The browser starts at the application, leaves for the provider, and returns to a registered callback URL. The callback must match the provider registration exactly, including scheme, host and path. Behind a reverse proxy, an incorrect external base URL can produce a callback that the provider rejects. Trust forwarded host headers only from your own proxy.
package in.aitrove.receipts;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
class WorkforceLoginSecurity {
@Bean
SecurityFilterChain workforceLogin(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/login").permitAll()
.requestMatchers("/receipts/**").authenticated()
.anyRequest().denyAll());
http.oauth2Login(Customizer.withDefaults());
return http.build();
}
}spring.security.oauth2.client.registration.workforce.client-id=${WORKFORCE_CLIENT_ID}
spring.security.oauth2.client.registration.workforce.client-secret=${WORKFORCE_CLIENT_SECRET}
spring.security.oauth2.client.registration.workforce.scope=openid,profile
spring.security.oauth2.client.provider.workforce.issuer-uri=${WORKFORCE_ISSUER_URI}The registration requires the OAuth2 client dependency and a trusted provider. Keep credentials out of source control. After login, the session cookie is an ambient browser credential: retain CSRF protection for writes. An ID token describes authentication to this client; it is not an access token to send to unrelated APIs.
Check the failure path
Test denied and expired sessions, an unexpected callback host, a user without a mapped local role, and logout. Redirects add network round trips and provider availability to sign-in latency; ordinary authenticated requests should not need to call the provider every time.
Common Mistakes
- Using an email string alone as permanent authorization without a local account policy.
- Logging client secrets, codes or tokens while debugging the callback.
- Disabling CSRF because the application also has bearer-token endpoints.
- Assuming a successful provider login grants access to every receipt.
Read next
Cookie sessions and CSRF, request matcher order, and receipt ownership.
