Springboot通过cors解决跨域问题(解决spring security oath2的/oauth/token跨域问题)

在工程里添加两个类:
CorsConfig.java: 实现全局过滤器,设置CORS,注意一定要是全局。网上说多加一个注解(Spring官网)或者加Cors Mapper只能解决自定义接口的跨域,对于spring security oath2的默认接口,例如 /oauth/token跨域问题,是无法解决的,必须通过本文的全局CORS Filter解决。

package com.qiaoya.interceptor;

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);
    }
}

WebSecurityConfig.java:
配置服务器允许 /oauth/token的option方法,因为/oauth/token接口是先发一个option请求,然后再发正式post请求,如果是option接口不被允许,就返回401。这里比较关键,网上的解决方案说了这个地方,但是基本没说清楚怎么放放哪里,所以直接上代码,把整个类copy到工程就可以使用了。

package com.qiaoya.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author Cowin
 * @since 20170628
 * */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(-1)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers().antMatchers(HttpMethod.OPTIONS, "/oauth/token", "/rest/**", "/api/**", "/**")
        .and()
        .csrf().disable();
    }
}

你可能感兴趣的:(开源服务器)