Spring Security Basics
IntermediateSpring Security protects your application through a chain of servlet filters. Understanding the SecurityFilterChain, SecurityContext, and HttpSecurity DSL is the foundation for any authentication or authorization implementation.
Overview
Spring Security intercepts every HTTP request through a FilterChainProxy — a servlet filter that delegates to a chain of Security Filters. Each filter handles one concern: authentication, session management, CSRF, headers, etc. The authenticated principal is stored in SecurityContextHolder (thread-local). The HttpSecurity DSL in a @Bean of type SecurityFilterChain lets you configure which URLs require authentication, which authentication mechanisms to use, and which filters to add or remove.
SecurityFilterChain — The Core DSL
Define a SecurityFilterChain @Bean to replace Spring Security's defaults. A stateless REST API disables session creation and CSRF (because there are no cookies), and configures a JWT filter instead.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
// Disable CSRF for stateless REST APIs (tokens, not cookies)
.csrf(AbstractHttpConfigurer::disable)
// No session — stateless JWT authentication
.sessionManagement(s -> s
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// URL access rules — order matters: specific before general
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/v1/auth/**").permitAll() // public
.requestMatchers("/api/v1/admin/**").hasRole("ADMIN") // admin only
.requestMatchers(HttpMethod.GET, "/api/v1/courses/**").permitAll()
.anyRequest().authenticated() // everything else requires auth
)
// Add JWT filter before the default UsernamePasswordAuthenticationFilter
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
}SecurityContext and SecurityContextHolder
After authentication, the principal is stored in the SecurityContext, held by SecurityContextHolder (thread-local). You can access it anywhere in the request thread to get the current user.
// Accessing the current user in a service or controller
@Service
public class UserService {
public UserDto getCurrentUserProfile() {
// Get from SecurityContext — set by the JWT filter
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String userId = (String) auth.getPrincipal(); // whatever your filter sets
return userRepository.findById(userId)
.map(userMapper::toDto)
.orElseThrow();
}
}
// Cleaner: inject via @AuthenticationPrincipal in controller
@RestController
@RequestMapping("/api/v1/me")
public class ProfileController {
@GetMapping
public UserDto getMyProfile(
@AuthenticationPrincipal String userId) { // injected from SecurityContext
return userService.findById(userId);
}
}
// Or: resolve from JWT payload using a custom annotation
// (implement HandlerMethodArgumentResolver for complex cases)Key Points to Remember
- 1Spring Security is a chain of servlet filters — every request passes through SecurityFilterChain.
- 2Disable CSRF for stateless REST APIs that use tokens instead of cookies.
- 3SessionCreationPolicy.STATELESS prevents Spring Security from creating HTTP sessions.
- 4URL access rules are evaluated in order — specific paths must come before general ones.
- 5SecurityContextHolder is thread-local — it holds the authenticated principal for the current request.
- 6@AuthenticationPrincipal injects the principal directly into a controller method parameter.
Interview Questions
Sign in to ask AriaWhat is the Spring Security FilterChain and how does it work?
Why do we disable CSRF for REST APIs?
What is SecurityContextHolder and why is it thread-local?
How would you allow unauthenticated access to some endpoints but require auth for others?
What is the difference between authentication and authorization in Spring Security?
Ask Aria about Spring Security Basics
Your personal AI tutor — ask anything about this concept
Revision Status
Personal Notes
Sign in to save personal notes for this topic.
Discussion
Sign in to join the discussion.