ZPY博客

Spring Security Oauth2.0 ajax post请求跨域的解决方法

最近项目中有单点登录的需求,用的是Spring Security Oauth2.0框架,授权的服务端已经写好,用postman测的也没问题。但是新建一个工程来获取token,就会报跨域的错。网上找了半天,发现写的都不是很全,有些注意的地方没有说的很清楚,特此记录。

首先,增加一个CorsFilter的过滤器

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}

然后,在WebSecurityConfigurerAdapter的继承类里加上允许OPTIONS 方法,最后最关键的一点是,需要把@Order(1)改为@Order(-1)!!!!我就是没有设这一步导致怎么样都不行。改为-1后就可以正常得到token了。

@Configuration
@Order(-1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .antMatchers(HttpMethod.OPTIONS,"/login", "/oauth/authorize", "/oauth/token")
                .and()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll()
                .and()
                .cors()
                .and()
                .csrf().disable();
    }