java的方式配置spring security:
配置方式:
一,继承AbstractSecurityWebApplicationInitializer
public class SecurityWebInitializer extends AbstractSecurityWebApplicationInitializer{
}
上述操作,相当于加了一个过滤器,并把所有过滤传递给springSecurityFilterChain bean
二,配置SecurityConfig
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
上述操作,就是security的配合类了,下面代码是@EnableWebSecurity注解的内容
@Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value={java.lang.annotation.ElementType.TYPE})
@Documented
@Import({WebSecurityConfiguration.class,ObjectPostProcessorConfiguration.class})
@EnableGlobalAuthentication
public @interface EnableWebSecurity {
/**
* Controls debugging support for Spring Security. Default is false.
* @return if true, enables debug support with Spring Security
*/
boolean debug() default false;
}
这里值得注意的是引入的WebSecurityConfiguration.class
@Bean(name=AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)
public Filter springSecurityFilterChain() throws Exception {
boolean hasConfigurers = webSecurityConfigurers != null && !webSecurityConfigurers.isEmpty();
if(!hasConfigurers) {
throw new IllegalStateException("At least one non-null instance of "+ WebSecurityConfigurer.class.getSimpleName()+" must be exposed as a @Bean when using @EnableWebSecurity. Hint try extending "+ WebSecurityConfigurerAdapter.class.getSimpleName());
}
return webSecurity.build();
}
public static final String DEFAULT_FILTER_NAME = "springSecurityFilterChain";
上述两段代码不难看出,我们用来过滤请求的bean(springSecurityFilterChain)就是在这里定义的。
三,注册SecurityConfig,SecurityConfig类这样写在这里系统是识别不出来的,如果用的是spring mvc的话,需要在继承了AbstractAnnotationConfigDispatcherServletInitializer类的下述方法里声明一下,这样beanfactory才会把相关的bean注册进去。
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class,SecurityConfig.class};
常见错误
No bean named 'springSecurityFilterChain' is defined
按照上述第三步,在rootconfigclasses里加上SecurityConfig.class