Springboot通過cors解決跨域問題(解決spring security oath2的/oauth/token跨域問題)
阿新 • • 發佈:2019-02-19
在工程裡新增兩個類:
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();
}
}