微信oauth授权ajax跨域,Spring Security Oauth2.0 ajax post请求跨域的解决方法 | ZPY博客...
最近项目中有单点登录的需求,用的是Spring Security Oauth2.0框架,授权的服务端已经写好,用postman测的也没问题。但是新建一个工程来获取token,就会报跨域的错。网上找了半天,发现写的都不是很全,有些注意的地方没有说的很清楚,特此记录。首先,增加一个CorsFilter的过滤器。import org.springframework.context.annotation.
最近项目中有单点登录的需求,用的是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();
}

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)