項目技術(shù)架構(gòu):
前端:vue
后端:springcloud h版
1沟堡、網(wǎng)關(guān):gateway
( 1)作為所有資源的統(tǒng)一訪問入口,需要支持跨域
(2)依賴oauth2创橄,使用resource相關(guān)api烘跺,同時作為資源服務(wù)器闹击,進(jìn)行權(quán)限認(rèn)證
當(dāng)寫好接口后,本機(jī)使用postman測試凹联,接口都正常返回沐兰,但配合前端測試時,一直出現(xiàn)下面兩個問題匕垫,而前端使用proxy代理僧鲁,也仍然無法解決。
問題一:
訪問XMLHttpRequest at'http://ip:port/randCodeImage?_method=get'來源'http://localhost:8081'已被CORS策略阻止:'Access Control Allow Origin'標(biāo)頭包含多個值“象泵,”寞秃,但只允許一個值。
問題二:
Access to XMLHttpRequest at 'http://ip:port/userInfo' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
最初解決辦法
1偶惠、配置yml春寿,針對問題一,查閱相關(guān)資料后忽孽,可以只保留一個绑改。問題一可以解決
spring:
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]':
# 允許攜帶認(rèn)證信息
allow-credentials: true
# 允許跨域的源(網(wǎng)站域名/ip),設(shè)置*為全部
allowedOrigins: "*"
# 允許跨域的method兄一, 默認(rèn)為GET和OPTIONS厘线,設(shè)置*為全部
allowedMethods: "*"
# 允許跨域請求里的head字段,設(shè)置*為全部
allowedHeaders: "*"
default-filters:
#相同header多個值時的處理方式出革,三種規(guī)則可選(RETAIN_FIRST|RETAIN_UNIQUE|RETAIN_LAST)
- DedupeResponseHeader=Access-Control-Allow-Origin Access-Control-Allow-Credentials, RETAIN_FIRST
DedupeResponseHeader的源碼見:org.springframework.cloud.gateway.filter.factory.DedupeResponseHeaderGatewayFilterFactory
但問題二造壮,不論是自己寫跨域過濾器,還是調(diào)整yml的配置骂束,都得不到解決耳璧。百思不得其解。
最終解決辦法:關(guān)掉ResourceServerConfig的跨域配置展箱,并且引入自定義的跨域過濾器
1旨枯、百度后,有人說要關(guān)掉weblfux的跨域混驰,但不知道如何關(guān)攀隔。
2皂贩、后來發(fā)現(xiàn),瀏覽器在發(fā)起options 探測請求時竞慢,一直被網(wǎng)關(guān)阻止先紫,出現(xiàn)了401錯誤,懷疑可能是oauth2引起的筹煮。結(jié)合1中的提法,嘗試引入oauth2的跨域配置居夹,引入自定義跨域過濾器败潦,問題二得到解決。
關(guān)鍵代碼:
// 引入跨域
http.cors().and().csrf().disable();
// 增加自定義攔截器
http.addFilterAt(new CorsFilter(), SecurityWebFiltersOrder.SECURITY_CONTEXT_SERVER_WEB_EXCHANGE);
附最終代碼:
SecurityWebFilterChain配置
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
// 關(guān)掉跨域
http.cors().and().csrf().disable();
// 增加自定義攔截器
http.addFilterAt(new CorsFilter(), SecurityWebFiltersOrder.SECURITY_CONTEXT_SERVER_WEB_EXCHANGE);
http.oauth2ResourceServer().jwt()
.jwtAuthenticationConverter(jwtAuthenticationConverter());
// 如果是token過期了准脂,需要加到oauth2ResourceServer上劫扒,才會起作用,下面不知道為什么不起作用
http.oauth2ResourceServer().authenticationEntryPoint(restAuthenticationEntryPoint);
http.authorizeExchange()
.pathMatchers(ArrayUtil.toArray(ignoreUrlsConfig.getUrls(), String.class)).permitAll()//白名單配置
.pathMatchers("/login", "/new/login", "/webjars/**",
"/js/**", "/config/**", "/images/**", "/css/**", "/commonlib/**", "/thirdlibs/**",
"/favicon.ico", "/loginServer/**", "/randCodeImage/**",
"/oauth/**", "*.js", "/**/*.json", "/**/*.css", "/**/*.js", "/portal/**", "/**/*.map", "/**/*.html",
"/**/*.png", "uum/region/enum/**").permitAll()
.anyExchange().access(authorizationManager)//鑒權(quán)管理器配置
.and().exceptionHandling()
.accessDeniedHandler(restfulAccessDeniedHandler)//處理未授權(quán)
.authenticationEntryPoint(restAuthenticationEntryPoint)//處理未認(rèn)證
.and().headers().frameOptions().disable() //允許iframe
;
return http.build();
}
CorsFilter定義:
@Configuration
public class CorsFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange ctx, WebFilterChain chain) {
ServerHttpRequest request = ctx.getRequest();
if (CorsUtils.isCorsRequest(request)) {
ServerHttpResponse response = ctx.getResponse();
HttpHeaders headers = response.getHeaders();
headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*");
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "");
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "false");
headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600");
if (request.getMethod() == HttpMethod.OPTIONS) {
response.setStatusCode(HttpStatus.OK);
return Mono.empty();
}
}
return chain.filter(ctx);
}
}