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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A SecurityFilterChain bean is where you declare which routes are public and how login and logout behave.
- 2Wrapping the default OidcUserService lets you add custom authorities derived from token claims.
- 3Once login succeeds, the OidcUser can be injected straight into controllers as the authentication principal.
Related explainers
java
public final class IbanValidator { private static final Map<String, Integer> COUNTRY_LENGTHS = Map.ofEntries( Map.entry("DE", 22), Map.entry("FR", 27), Map.entry("GB", 22),
Validating IBANs with the mod-97 checksum
validation
checksum
modular-arithmetic
Intermediate
8 steps
php
<?php namespace App\Http\Middleware;
Verifying GitHub webhook signatures in Laravel
middleware
hmac
webhooks
Intermediate
5 steps
java
@RestController @RequestMapping("/api/reports") public class OrderReportController {
Streaming a CSV export in Spring
streaming
csv-export
backpressure
Intermediate
9 steps
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-oidc-login-works-in-spring-security-explained-java-1e25/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.