灵异事件?我的Security配置怎么不生效?为什么一直跳转登录页面?
因为工作需要,项目中需要引入Spring Security这个安全框架(只是单纯的引入),刚开始觉得好简单,引入完之后在启动类上面把Security自动配置类排除掉不就行了吗?
说干就干,引入了Security依赖之后,我在@SpringBootApplication注解的参数exclude中将SecurityAutoConfiguration这个自动配置类排除掉,如果项目中引入了健康检查的依赖还需要将ManagementWebSecurityAutoConfiguration这个自动配置类排除,因为在ManagementWebSecurityAutoConfiguration这个自动配置类中他会开启Security的自动配置。
弄完了,就这么简单!打包,发布,测试,没问题。
紧接着,轮到给网关服务添加Security依赖,有了前面的经验,CV大法一气呵成,紧接着打包、发布、测试,漂亮,喜提加班!!它居然让我登录?怎么跟我预期的不一样?
紧接着分析问题,Security是由一组过滤器组成的过滤器链构成的,默认情况下它会把认证成功的信息存储到Session对象中,下次再来根据Session中是否存在个人信息来判断你是否已经认证过,我看到在其它服务里面按照我先前的操作它的Spring容器中是没有springSecurityFilterChain这个对象的,但是我网关服务里面居然还有!那这个道路走不通,转换思维,让这个认证的过滤器失效?怎么让他失效呢?放行!!
让所有资源都放行!
说干就干,于是就写了一个Security的配置类!
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig2 extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.csrf()
.disable()
.cors();
}
}
写完,心里美滋滋,想着可以收工了,打包、发布、测试,what?怎么还要我登录?是不是我打包姿势出线问题了?我重新打包、发布、测试,还是要我登录?我这个配置写的有问题?那行,我直接让所有请求不走过滤器,我又重新写了配置!
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig2 extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.csrf()
.disable()
.cors();
}
}
又一次打包、发布、测试,发现问题还是解决不了!心里有点急了,今晚打王者看来是没希望了!
于是突然想起这是个网关服务!!Gateway跟Security好像有点不兼容!想到这我才想起来,在引入Gateway的时候我们需要排除掉spring-boot-starter-web这个依赖,因为它们的一个是webflux,一个是mvc,此时想到既然如此,那配置方式是不是应该也不一样呢?然后去看了下官方介绍,发现果然还有别的配置方式!
于是又重新写了个配置类
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity httpSecurity){
httpSecurity
.authorizeExchange()
.pathMatchers("/**").permitAll()
.pathMatchers(HttpMethod.OPTIONS).permitAll()
.anyExchange().authenticated()
.and()
.csrf()
.disable()
.cors();
return httpSecurity.build();
}
}
打包、发布、测试,OK,问题解决!下班了!
被这个问题坑的有点惨!