Spring Boot: From Basics to Production · Securing APIs with Spring Security

How Spring Security Works

Configure the SecurityFilterChain with the lambda DSL.

Spring Security is a chain of servlet filters. Adding the starter secures every endpoint by default. Configure behavior by declaring a SecurityFilterChain bean: which requests need authentication or roles (authorizeHttpRequests), how users authenticate (form login, HTTP Basic, OAuth2/JWT), session policy, CORS and CSRF. Rules are evaluated in order — put specific matchers before general ones and end with anyRequest().authenticated().

@Configuration
@EnableWebSecurity
class SecurityConfig {
    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        return http
                .securityMatcher("/api/**")
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(HttpMethod.GET, "/api/v1/products/**").permitAll()
                        .requestMatchers("/api/v1/admin/**").hasRole("ADMIN")
                        .anyRequest().authenticated())
                .oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()))
                .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .csrf(csrf -> csrf.disable())          // stateless token API, no cookies
                .build();
    }
}

Common pitfalls

  • anyRequest().permitAll() left in by accident.
  • Disabling CSRF for cookie/session-based apps.
  • Ordering a broad matcher before specific ones.

Key points

  • Security is a filter chain
  • Declare SecurityFilterChain beans
  • Order matchers specific → general; deny by default

Further reading: Spring Security: Architecture

Practice questions

When is it acceptable to disable CSRF protection?

Answer

For stateless APIs authenticated with tokens in the Authorization header (no cookies). Browser apps using session cookies need CSRF protection.

What does hasRole('ADMIN') check?

Answer

That the authentication has the authority ROLE_ADMIN (Spring adds the ROLE_ prefix for role checks).

Open in the app to mark lessons complete, take notes and track your progress.