使用浏览器跨域访问spring security api时,会先发起 options的请求,但是该请求会直接被security 拦截,因为options请求没有携带token,所以直接返回401,就不会在发起get或post请求了。
解决方案:
1、配置HttpSecurity不校验:antMatchers(HttpMethod.OPTIONS).permitAll()
@Override
public void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll() // 对option不校验
.anyRequest().authenticated();
}
2、如果使用的使用ZuulFilter解决跨域问题,可以提高该filter的order。