Skip to main content

Securing Web Apps and REST APIs

Spring Security executes its structural defense by deploying a chain of standard Servlet Filters. These filters execute sequentially before the request ever reaches the Spring DispatcherServlet.

Standard Form Boot Configuration

To secure a standard Web Application serving Thymeleaf pages, you install the spring-boot-starter-security wrapper. By default, it locks down every single mapped URL endpoint entirely.

To customize exactly which endpoints are locked versus public, you create a SecurityFilterChain bean globally.

@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
// Anyone can visit the exact homepage natively or login cleanly
.requestMatchers("/", "/login", "/css/**").permitAll()
// All other requests require a logged-in user
.anyRequest().authenticated()
)
.formLogin(form -> form
.loginPage("/login").permitAll()
);

return http.build();
}
}

Securing Stateless REST APIs

Standard web applications rely on server-side Session cookies. REST APIs are strictly stateless. They do not use Cookies.

For REST APIs, you must parse external tokens. The standard practice utilizes specific OAuth2 Resource Server setups intercepting JWT tokens passed in the HTTP Authorization: Bearer <token> header.

http
// Disable standard Sessions entirely
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// Validate incoming JWT signatures
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));