Contents 12 sections
- How to use this guide
- Architecture diagrams
- What is Spring Security?
- Spring Boot project setup
- Configuring the SecurityFilterChain
- Implementing the JWT filter
- UserDetailsService
- Role-based authorization
- Method Security
- OAuth2 social login
- Security testing
- Frequently asked questions
How to use this guide
How to read itUnderstanding Spring Security as a real-world workflow
Build a practical security architecture with Spring Security 6 on Spring Boot: JWT authentication, OAuth2 social login, role-based authorization, Method Security, CSRF defense, and testing. Rather than listing concepts, this guide is organized so you can follow the content in the order you have to make decisions on a real project.
Key perspectiveBackend / systems development
Before syntax, pin down the boundaries a request crosses: validation, processing, storage, and response.
JWT authentication serversOAuth2 social loginRole/Permission authorizationSpring Boot security
Architecture diagrams
To make what you read stick, it helps to capture the flow as a picture first. The two diagrams below are reference maps you can keep coming back to while learning Spring Security.
Learning flow
Architecture view
What is Spring Security?
When you first open Spring Security, the big picture matters more than individual commands. This section starts with the problems the concepts ahead were created to solve.
Spring Security is the security framework responsible for authentication and authorization in Spring Boot applications. It works on a filter chain and supports JWT, OAuth2, and session-based approaches alike.
Spring Boot project setup
Here you look at Spring Boot project setup alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Add Spring Security, Spring Data JPA, Validation, and Lombok in Spring Initializr.
plugins {
id("java")
id("org.springframework.boot") version "3.3.5"
id("io.spring.dependency-management") version "1.1.6"
}
java { toolchain { languageVersion.set(JavaLanguageVersion.of(21)) } }
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("io.jsonwebtoken:jjwt-api:0.12.6")
runtimeOnly("io.jsonwebtoken:jjwt-impl:0.12.6")
runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.12.6")
compileOnly("org.projectlombok:lombok")
annotationProcessor("org.projectlombok:lombok")
runtimeOnly("com.h2database:h2")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.springframework.security:spring-security-test")
}
Configuring the SecurityFilterChain
Here you look at Configuring the SecurityFilterChain alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
In Spring Boot 3.x / Security 6, you register a SecurityFilterChain bean directly instead of using WebSecurityConfigurerAdapter. A request passes through several filters in order, and the custom JWT filter is placed ahead of the standard authentication filter so the token is verified first and the SecurityContext is populated.
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final JwtAuthenticationFilter jwtAuthFilter;
private final UserDetailsService userDetailsService;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable())
.sessionManagement(sm -> sm.sessionCreationPolicy(STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
@Bean
public AuthenticationProvider authenticationProvider() {
var provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);
provider.setPasswordEncoder(passwordEncoder());
return provider;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config)
throws Exception {
return config.getAuthenticationManager();
}
}
Implementing the JWT filter
Here you look at Implementing the JWT filter alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Extend OncePerRequestFilter to extract the Authorization header from every request and verify the token. As the name says, this filter is guaranteed to run exactly once per request, and because it fills the authentication information into SecurityContextHolder directly, the currently signed-in user can be looked up afterward anywhere in controllers and services with @AuthenticationPrincipal and the like.
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtService jwtService;
private final UserDetailsService userDetailsService;
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
final String authHeader = request.getHeader("Authorization");
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
filterChain.doFilter(request, response);
return;
}
final String jwt = authHeader.substring(7);
final String username = jwtService.extractUsername(jwt);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (jwtService.isTokenValid(jwt, userDetails)) {
var authToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities()
);
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
filterChain.doFilter(request, response);
}
}
UserDetailsService
Here you look at UserDetailsService alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Implement UserDetailsService to load user information from the database. During authentication Spring Security calls only loadUserByUsername on this interface, so wherever the real user information lives, in a database or an external API, implementing this one place is enough and the framework handles the rest of the authentication logic identically.
@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return userRepository.findByEmail(email)
.orElseThrow(() -> new UsernameNotFoundException("User not found: " + email));
}
}
// User Entity — implements UserDetails
@Entity @Table(name = "users")
@Getter @Builder @NoArgsConstructor @AllArgsConstructor
public class User implements UserDetails {
@Id @GeneratedValue(strategy = IDENTITY) private Long id;
private String name;
@Column(unique = true) private String email;
private String password;
@Enumerated(STRING) private Role role;
@Override public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of(new SimpleGrantedAuthority("ROLE_" + role.name()));
}
@Override public String getUsername() { return email; }
@Override public boolean isAccountNonExpired() { return true; }
@Override public boolean isCredentialsNonExpired() { return true; }
@Override public boolean isEnabled() { return true; }
}
Role-based authorization
Here you look at Role-based authorization alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Roles are checked per HTTP request or per method. The basic principles are to open APIs called before authentication, such as sign-up and login, with permitAll in SecurityConfig, and never to store passwords as plain text, leaving only the value hashed by a PasswordEncoder in the database.
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {
private final AuthService authService;
@PostMapping("/register")
@ResponseStatus(HttpStatus.CREATED)
public AuthResponse register(@Valid @RequestBody RegisterRequest req) {
return authService.register(req);
}
@PostMapping("/login")
public AuthResponse login(@Valid @RequestBody LoginRequest req) {
return authService.login(req);
}
}
// Login service
@Service @RequiredArgsConstructor
public class AuthService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final JwtService jwtService;
private final AuthenticationManager authManager;
public AuthResponse register(RegisterRequest req) {
var user = User.builder()
.name(req.getName())
.email(req.getEmail())
.password(passwordEncoder.encode(req.getPassword()))
.role(Role.USER)
.build();
userRepository.save(user);
return new AuthResponse(jwtService.generateToken(user));
}
public AuthResponse login(LoginRequest req) {
authManager.authenticate(
new UsernamePasswordAuthenticationToken(req.getEmail(), req.getPassword()));
var user = userRepository.findByEmail(req.getEmail()).orElseThrow();
return new AuthResponse(jwtService.generateToken(user));
}
}
Method Security
Here you look at Method Security alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Enabling @EnableMethodSecurity lets you apply @PreAuthorize and @PostAuthorize to service methods.
@Service
@PreAuthorize("isAuthenticated()")
public class PostService {
@PreAuthorize("hasRole('ADMIN') or #userId == authentication.principal.id")
public List<Post> findByUser(Long userId) { ... }
@PreAuthorize("hasRole('ADMIN')")
public void deleteAll() { ... }
@PostAuthorize("returnObject.author == authentication.name")
public Post findById(Long id) { ... }
}
OAuth2 social login
Here you look at OAuth2 social login alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Add spring-boot-starter-oauth2-client and set the client information in application.yml to implement social login with Google and other providers (GitHub, Kakao, Naver, and so on). Our server never handles the password of the user directly; it exchanges the Authorization Code issued by Google for an Access Token and receives only the user information.
spring:
security:
oauth2:
client:
registration:
google:
client-id: ${GOOGLE_CLIENT_ID}
client-secret: ${GOOGLE_CLIENT_SECRET}
scope: openid, profile, email
@Service
public class CustomOAuth2UserService extends DefaultOAuth2UserService {
private final UserRepository userRepository;
@Override
public OAuth2User loadUser(OAuth2UserRequest request) throws OAuth2AuthenticationException {
OAuth2User oAuth2User = super.loadUser(request);
String email = oAuth2User.getAttribute("email");
String name = oAuth2User.getAttribute("name");
User user = userRepository.findByEmail(email)
.orElseGet(() -> userRepository.save(
User.builder().email(email).name(name).role(Role.USER).build()
));
return new DefaultOAuth2User(
List.of(new SimpleGrantedAuthority("ROLE_" + user.getRole())),
oAuth2User.getAttributes(), "email"
);
}
}
Security testing
Here you look at Security testing alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Inject an authentication context with @WithMockUser or @WithUserDetails and verify the security configuration with MockMvc. Without going through issuing and verifying a real JWT in every test, you can quickly check, in a state assumed to be already authenticated, that access control per permission (403/401 responses and so on) behaves as intended.
@SpringBootTest
@AutoConfigureMockMvc
class SecurityTest {
@Autowired MockMvc mvc;
@Test
void protectedPath_withoutAuth_returns401() throws Exception {
mvc.perform(get("/api/users"))
.andExpect(status().isUnauthorized());
}
@Test
@WithMockUser(roles = "USER")
void regularUser_canListUsers() throws Exception {
mvc.perform(get("/api/users"))
.andExpect(status().isOk());
}
@Test
@WithMockUser(roles = "USER")
void regularUser_cannotAccessAdminEndpoint() throws Exception {
mvc.perform(delete("/api/admin/users/1"))
.andExpect(status().isForbidden());
}
@Test
@WithMockUser(roles = "ADMIN")
void admin_canDelete() throws Exception {
mvc.perform(delete("/api/admin/users/1"))
.andExpect(status().isNoContent());
}
}
Spring Security: frequently asked questions
What is the difference between authentication and authorization?
Authentication confirms who the requesting user is, and authorization decides whether that user may access the resource. Logging in is authentication, and blocking a page only administrators may see is authorization. A failed authentication returns 401 and a failed authorization returns 403.
Should I choose sessions or JWT?
For a traditional web application where the server also renders the pages, sessions are simple and logout is easy. JWT fits mobile apps and architectures where several services share the same authentication. A JWT is hard to invalidate once issued, so the design needs short expiry times together with refresh tokens.
Can I turn off CSRF protection for a REST API?
An API that authenticates only with a token in the Authorization header, and not with cookies the browser sends automatically, is not a CSRF target, so it can be turned off. If a session or token is carried in a cookie, keep CSRF protection on.