Spring Cloud GateWay跨域处理

近来开发SpringCloud 微服务 +Vue 前后端分离项目,期间遇见了跨域问题,记录下自己解决的手段

@Slf4j
@Configuration
public class CorsFilter implements WebFilter {

    @Autowired
    CorsFilterConfiguration corsFilterConfiguration;

    private static final String ALLOWED_EXPOSE = "*";

    @Override
    public Mono filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (CorsUtils.isCorsRequest(request)) {
            ServerHttpResponse response = exchange.getResponse();
            String origin = request.getHeaders().getFirst(HttpHeaders.ORIGIN);
            if (!allowOrigin(origin)) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                return response.writeWith(Mono.just(getFailureResponseBody(exchange, 403,
                        "跨域禁止访问")));
            }
            HttpHeaders httpHeaders = response.getHeaders();
            httpHeaders.add("Access-Control-Allow-Headers", corsFilterConfiguration.getAllowHeaders());
            httpHeaders.add("Access-Control-Allow-Methods", corsFilterConfiguration.getMethods());
            httpHeaders.add("Access-Control-Allow-Origin", origin);
            httpHeaders.add("Access-Control-Expose-Headers", ALLOWED_EXPOSE);
            httpHeaders.add("Access-Control-Max-Age", String.valueOf(corsFilterConfiguration.getMaxAge()));
            httpHeaders.add("Access-Control-Allow-Credentials", String.valueOf(corsFilterConfiguration.getAllowCredentials()));
            if (request.getMethod().name().equals(HttpMethod.OPTIONS.name())) {
                response.setStatusCode(HttpStatus.OK);
                return Mono.empty();
            }
        }
        return chain.filter(exchange);
    }


    boolean allowOrigin(String host) {
        if (StringUtils.isEmpty(host)) {
            return false;
        }
        Set allowOrigins = corsFilterConfiguration.getAllowOrigins();
        if (allowOrigins == null || allowOrigins.size() == 0) {
            return true;
        }
        return allowOrigins.contains(host);
    }

    private DataBuffer getFailureResponseBody(ServerWebExchange exchange, Integer code, String message) {
        ServerHttpResponse response = exchange.getResponse();
        JSONObject json =new JSONObject();
        json.put("code",code);
        json.put("message",message);
        //把json信息转译成UTF_8格式的字节
        byte[] bits = json.toJSONString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return buffer;

    }
}


@Component
@ConfigurationProperties(prefix = "spring.cloud.gateway.cors-filter")
class CorsFilterConfiguration {
    private String allowHeaders = "x-requested-with, Content-Type, Cache-Control,Authorization, credential, X-XSRF-TOKEN, authKey,tenantId,appType,version";
    private Set allowOrigins;
    private String methods = "*";
    private Long maxAge = 18000L;
    private Boolean allowCredentials = true;

    public String getAllowHeaders() {
        return allowHeaders;
    }

    public void setAllowHeaders(String allowHeaders) {
        this.allowHeaders = allowHeaders;
    }

    public Set getAllowOrigins() {
        return allowOrigins;
    }

    public void setAllowOrigins(Set allowOrigins) {
        this.allowOrigins = allowOrigins;
    }

    public String getMethods() {
        return methods;
    }

    public void setMethods(String methods) {
        this.methods = methods;
    }

    public Long getMaxAge() {
        return maxAge;
    }

    public void setMaxAge(Long maxAge) {
        this.maxAge = maxAge;
    }

    public Boolean getAllowCredentials() {
        return allowCredentials;
    }

    public void setAllowCredentials(Boolean allowCredentials) {
        this.allowCredentials = allowCredentials;
    }

你可能感兴趣的:(Spring,Cloud开发日记)