CORS筆記

1,網關跨域配置

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * @author yugj
 * @date 2021/12/7 15:30.
 */
@Configuration
public class SisyphusCorsConfiguration {

    @Value("${response.cors.allowedHeaders}")
    private String allowedHeaders;

    private static final String ALLOWED_METHODS = "GET, PUT, POST, DELETE, OPTIONS";
    private static final String ALLOWED_ORIGIN = "http://api.demo.cn";

    @Bean
    public WebFilter corsFilter() {
        return (ServerWebExchange ctx, WebFilterChain chain) -> {
            ServerHttpRequest request = ctx.getRequest();
            String origin = request.getHeaders().getOrigin();
            if (origin == null) {
                origin = ALLOWED_ORIGIN;
            }
            //允許所有請求跨域
            if (CorsUtils.isCorsRequest(request)) {
                ServerHttpResponse response = ctx.getResponse();

                HttpHeaders headers = response.getHeaders();
                headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
                headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, ALLOWED_METHODS);
                headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, allowedHeaders);

                headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
                if (request.getMethod() == HttpMethod.OPTIONS) {
                    response.setStatusCode(HttpStatus.OK);
                    return Mono.empty();
                }
            }
            return chain.filter(ctx);
        };
    }

}

說明:

ACCESS_CONTROL_ALLOW_CREDENTIALS, "true" 該屬性將允許跨域設置cookie,ACCESS_CONTROL_ALLOW_ORIGIN不能爲*,需要根據客戶端請求設置origin,ACCESS_CONTROL_ALLOW_HEADERS在option請求過來,將探測允許請求的header頭,若服務端未返回給客戶端,流量器將提示頭信息不在允許範圍

2,前端測試代碼

var xhr = new XMLHttpRequest();
xhr.open('post', 'http://88.localhost.cn:8089/api/x-account/userapi/loginphone',false);
xhr.setRequestHeader("appId", "2");
xhr.setRequestHeader("poolId", "2");
xhr.setRequestHeader("api-tag", "xxx");

xhr.setRequestHeader("content-type", "application/json");
xhr.withCredentials=true; // 該屬性允許跨域cookie傳輸到服務端,允許跨域設置響應cookie(同一個根域名下)
xhr.send('{"code":"xx","phone":"xxx"}');
console.log(xhr.responseText);
console.log(xhr.getAllResponseHeaders());

cookie在http協議中基於header頭傳輸,key爲Set-Cookie 值格式

"%s=%s; domain=%s; path=%s"; // key=value; domain=xxx.google.com; path=/

 

參考文檔:

https://stackoverflow.com/questions/32500073/request-header-field-access-control-allow-headers-is-not-allowed-by-itself-in-pr

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章