配置中 @EnableWebSecurity 的原因 class
Reason for @EnableWebSecurity in the configuration class
我刚看了另一个问题 的答案,但我完全不明白为什么我们需要添加 @EnableWebSecurity
注释。
即使我从配置中删除 @EnableWebSecurity
,我的应用程序仍然有效。
假设我们要实现基于 JWT 的(rest api)或简单的基于登录的 mvc 应用程序。对于以下配置,我缺少什么?
@Component
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public UserDetailsService userDetailsService() {
return new MyCustomUserDetailsService();
}
@Bean
public PasswsordEncoder passwsordEncoder() {
return new BrcyptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// for the jwt authentication add jwt filter etc ..
// for the login based, override default login page, error page etc..
}
}
如果您没有使用 spring-boot 而只是一个纯粹的 spring 项目,您肯定需要添加 @EnableWebSecurity
以启用 spring-security.
但是如果您使用的是spring-boot 2.0+,则不需要自己添加,因为如果您忘记添加,spring-boot自动配置会自动为您添加。在幕后,它是由 WebSecurityEnablerConfiguration
完成的,它的 javadoc
也说明了这种行为,如下所示:
If there is a bean of type WebSecurityConfigurerAdapter, this adds the
@EnableWebSecurity annotation. This will
make sure that the annotation is present with default security
auto-configuration and also if the user adds custom security and
forgets to add the annotation.
我刚看了另一个问题 @EnableWebSecurity
注释。
即使我从配置中删除 @EnableWebSecurity
,我的应用程序仍然有效。
假设我们要实现基于 JWT 的(rest api)或简单的基于登录的 mvc 应用程序。对于以下配置,我缺少什么?
@Component
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public UserDetailsService userDetailsService() {
return new MyCustomUserDetailsService();
}
@Bean
public PasswsordEncoder passwsordEncoder() {
return new BrcyptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// for the jwt authentication add jwt filter etc ..
// for the login based, override default login page, error page etc..
}
}
如果您没有使用 spring-boot 而只是一个纯粹的 spring 项目,您肯定需要添加 @EnableWebSecurity
以启用 spring-security.
但是如果您使用的是spring-boot 2.0+,则不需要自己添加,因为如果您忘记添加,spring-boot自动配置会自动为您添加。在幕后,它是由 WebSecurityEnablerConfiguration
完成的,它的 javadoc
也说明了这种行为,如下所示:
If there is a bean of type WebSecurityConfigurerAdapter, this adds the @EnableWebSecurity annotation. This will make sure that the annotation is present with default security auto-configuration and also if the user adds custom security and forgets to add the annotation.