java 50 lines · 8 steps

How OIDC login works in Spring Security

A Spring Security config wires up OAuth2/OIDC login and enriches the authenticated user with a custom role based on claims.

Explained by highlit
1@Configuration
2@EnableWebSecurity
3public class OAuth2SecurityConfig {
4 
5 @Bean
6 public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
7 http
8 .authorizeHttpRequests(auth -> auth
9 .requestMatchers("/", "/error", "/webjars/**").permitAll()
10 .anyRequest().authenticated()
11 )
12 .oauth2Login(oauth2 -> oauth2
13 .userInfoEndpoint(userInfo -> userInfo
14 .oidcUserService(this.oidcUserService())
15 )
16 .defaultSuccessUrl("/dashboard", true)
17 )
18 .logout(logout -> logout
19 .logoutSuccessUrl("/")
20 .clearAuthentication(true)
21 );
22 return http.build();
23 }
24 
25 private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() {
26 OidcUserService delegate = new OidcUserService();
27 return userRequest -> {
28 OidcUser oidcUser = delegate.loadUser(userRequest);
29 String registrationId = userRequest.getClientRegistration().getRegistrationId();
30 Set<GrantedAuthority> authorities = new LinkedHashSet<>(oidcUser.getAuthorities());
31 if (Boolean.TRUE.equals(oidcUser.getClaimAsBoolean("email_verified"))) {
32 authorities.add(new SimpleGrantedAuthority("ROLE_VERIFIED"));
33 }
34 return new DefaultOidcUser(authorities, oidcUser.getIdToken(), oidcUser.getUserInfo());
35 };
36 }
37}
38 
39@Controller
40class DashboardController {
41 
42 @GetMapping("/dashboard")
43 public String dashboard(@AuthenticationPrincipal OidcUser principal, Model model) {
44 model.addAttribute("name", principal.getFullName());
45 model.addAttribute("email", principal.getEmail());
46 model.addAttribute("picture", principal.getClaimAsString("picture"));
47 model.addAttribute("issuer", principal.getIssuer());
48 return "dashboard";
49 }
50}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A SecurityFilterChain bean is where you declare which routes are public and how login and logout behave.
  2. 2Wrapping the default OidcUserService lets you add custom authorities derived from token claims.
  3. 3Once login succeeds, the OidcUser can be injected straight into controllers as the authentication principal.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How OIDC login works in Spring Security — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code