What is the difference between @EnableWebSecurity and @EnableWebMvcSecurity?

@EnableWebSecurity

The JavaDoc documentaion:

Add this annotation to an @Configuration class to have the Spring Security configuration defined in any WebSecurityConfigurer or more likely by extending the WebSecurityConfigurerAdapter base class and overriding individual methods.

@EnableWebMvcSecurity

The JavaDoc documentaion:

Add this annotation to an @Configuration class to have the Spring Security configuration integrate with Spring MVC.

  • What exactly does it mean to 'integrate with Spring MVC' ? What extra behaviors do I get?
  • I found guides & answers, which suggest that this annotation adds CSRF Tokens to Spring MVC Forms, is this the only thing it adds?

Solution 1:

As of Spring Security 4.0, @EnableWebMvcSecurity is deprecated. The replacement is @EnableWebSecurity which will determine adding the Spring MVC features based upon the classpath.

To enable Spring Security integration with Spring MVC add the @EnableWebSecurity annotation to your configuration.

source

Solution 2:

If you take a look at those classes, @EnableWebMvcSecurity actually adds the @EnableWebSecurity annotation in WebMvcSecurityConfiguration. Therefore, @EnableWebMvcSecurity does everything that @EnableWebSecurity does, and a bit more.

What more you ask?

If you look at WebMvcSecurityConfiguration, you will see that it adds an AuthenticationPrincipalArgumentResolver so that you can access the authentication principal by adding an annotation to a controller method argument. i.e.:

public String show(@AuthenticationPrincipal CustomUser customUser) {
    // do something with CustomUser
    return "view";
}

It also integrates with Spring Web MVC to add a CSRF token to forms.