微信oauth授权ajax跨域,Spring Security Oauth2.0 ajax post请求跨域的解决方法 | ZPY博客...

最近项目中有单点登录的需求,用的是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();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值