Skip to content

Spring MVC Security Pattern

Example: Basic Security Configuration (Spring Boot 3.x)

java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/public/**").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            )
                .httpBasic(withDefaults())
                .formLogin(withDefaults())
            .build();
    }
}

Guidelines

  • Use @EnableWebSecurity and use SecurityFilterChain bean (Spring Boot 3.x+) or extend WebSecurityConfigurerAdapter for (Spring Boot 2.x).
  • Define URL patterns and roles for access control.
  • Use form login, HTTP Basic, or OAuth2 as needed.
  • Store secrets and credentials securely (never in source code).
  • Use CSRF protection for state-changing endpoints.
  • Prefer stateless sessions for APIs (JWT, OAuth2).
  • Use method-level security (@PreAuthorize, @Secured) for fine-grained control.

References

Copyright © MSG Systems Romania AI Labs