Why this matters
- Adding
spring-boot-starter-securitysecures every endpoint by default — understanding the filter chain prevents accidental lockdown or exposure. - Authentication (who are you?) and authorization (what can you do?) are separate concerns with distinct configuration points.
- Security is non-negotiable for production BookStore deployments handling user data and orders.
Filter chain
L1 · FresherSpring Security is a chain of filters that runs before your controller — authentication first, then authorization.
Authentication vs authorization
L2 · IntermediateAuthentication proves who the caller is; authorization checks roles or scopes for /api/admin/** routes.
SecurityFilterChain bean
L3 · AdvancedBoot 3 uses a lambda DSL SecurityFilterChain bean to configure CSRF, session, and matcher rules in code.
Method security
L4 · Expert@PreAuthorize("hasRole('ADMIN')") on services adds a second layer beyond URL rules — mind proxy and @EnableMethodSecurity.
Add Spring Security
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Every endpoint now requires authentication. A default user user with a random password appears in the startup log.
SecurityFilterChain configuration
// learn:fragment
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/health", "/api/books/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.requestMatchers("/api/orders/**").authenticated()
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Authorization rules for BookStore
permitAll()— No authentication required. Health checks, public catalog browsing.authenticated()— Any logged-in user. Order placement, profile management.hasRole("ADMIN")— Specific role required. Inventory management, user administration.hasAuthority("SCOPE_read")— Fine-grained permission (OAuth2 scopes).
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 5 sections
- UserDetailsService
- Method-level security
- Password encoding
- Testing secured endpoints
- Security context
Test yourself
Answer these before moving on — recall is what makes it stick.