What are the options for implementing security in a Spring MVC application?

Spring Security is the standard way to secure a Spring MVC application, covering authentication (who you are) and authorization (what you can do), along with protections against common web attacks. It can be wired up with Java configuration or, in legacy apps, XML, and it plugs into the same filter chain that handles every incoming request.

Key Points: • @EnableWebSecurity plus a SecurityFilterChain bean configures which URLs require authentication and which roles can access them. • Method-level security uses @PreAuthorize, @PostAuthorize, or the older @Secured to protect individual service or controller methods. • CSRF protection is enabled by default for form-based apps and should stay on unless the app is a stateless API using tokens. • OAuth2 and OpenID Connect support single sign-on against providers like Google or Okta via spring-boot-starter-oauth2-client. • JWT-based authentication is common for stateless REST APIs, validating a bearer token on each request instead of using server-side sessions.

Example: A typical setup restricts /admin/** to users with the ADMIN role, allows /api/public/** for everyone, and requires authentication for everything else, all declared in one SecurityFilterChain bean.

Code Example:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(auth -> auth
            .requestMatchers("/admin/**").hasRole("ADMIN")
            .requestMatchers("/api/public/**").permitAll()
            .anyRequest().authenticated())
        .formLogin(Customizer.withDefaults());
    return http.build();
}

Interview Tip: A concise interview answer is:

"I secure Spring MVC apps with Spring Security, configuring a SecurityFilterChain bean to define which URLs need authentication or specific roles, and using @PreAuthorize for method-level checks. For stateless APIs I'd add JWT-based authentication, and for user-facing login I'd consider OAuth2 for single sign-on."