今天遇到了一个问题,在发起请求,经过SpringCloudGateway网关,然后转发到具体的微服务处理时,出现第一次请求通过,后面再请求同一个地址时,出现403拒绝访问的问题。
问题描述:
- 在header中携带token,并发起请求
- 将token解析后的用户信息,通过SecurityContextHolder.getContext().setAuthentication()保存在上下文环境中
- 请求结束后,发起第二次请求,发现Authentication中的Principal变成了“anonymousUser”
- 然后出现了403 forbidden的错误
解决方案:
//安全拦截机制
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/**").permitAll()
.anyRequest().authenticated()
.and().csrf().disable()
// 定制我们自己的 session 策略:调整为让 Spring Security 不创建和使用 session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
在拦截配置中加上sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS),调整为让 Spring Security 不创建和使用 session。
再次发起相同请求时,就不会再出现403 forbidden的问题了。
特此记录一下这个问题的解决方案,具体原因不详,待日后有空,再做深入研究。