CORS 配置在 Spring Cloud Gateway 中不起作用

问题描述 投票:0回答:1

从浏览器(jQuery 脚本)访问 API 被阻止。这是我收到的错误消息:

从源“null”访问“http://localhost:8765/conversion/convert”的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:无“Access-Control-Allow-” Origin' 标头存在于请求的资源上。

HTML 文件中的我的 jQuery 脚本:

$.ajax({
    type: 'POST',
    url: 'http://localhost:8765/conversion/convert',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer MY_JWT_TOKEN'
    },
    data: JSON.stringify({
        id: 1,
        from: 'usd',
        to: 'bdt',
        quantity: 100
    }),
    success: function(data) {
        console.log(data);
    },
    error: function(error) {
        console.error(error);
    }
});

Maven 依赖项和版本:

  1. spring-cloud-gateway:2022.0.4
  2. spring-cloud-starter-gateway:3.1.6
  3. spring-boot-starter-oauth2-资源服务器:3.1.6
  4. spring-cloud-starter-netflix-eureka-client

我已经使用 API 网关配置了 OAuth2 (Keycloak),并按照官方 Spring Cloud 页面上的指示在我的网关服务配置文件 (yml) 中使用了 CORS (globalcors) 配置。我也尝试了互联网上的所有不同方法,似乎没有任何效果。

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-ui: http://localhost:9000/realms/Microservices-demo-realm
          jws-algorithm: RS256
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "*"
            allowedMethods: "*"
            allowedHeaders: "*"
      default-filters:
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin RETAIN_UNIQUE
        - name: TokenRelay
      routes:
        - id: conversion-service
          uri: lb://currency-conversion
          predicates:
            - Path=/conversion/**

这是 Google Chrome 网络控制台:

我也尝试过一个小型的 ReactJS 应用程序,CORS 也被阻止了。这是截图:

请帮忙!

spring-boot spring-cloud-gateway http-status-code-401
1个回答
0
投票

无需进行 CORS 配置即可避免 CORS 错误的一个简单方法是具有相同的来源(也通过网关为您的网站提供服务,而不仅仅是 API)。

另外,这不是问题,但将网关配置为资源服务器是一个坏主意,特别是当它被浏览器中运行的某些 Javascript 代码查询时。

最好将其配置为具有

oauth2Login()
TokenRelay=
过滤器的客户端。网关后面的 REST API 将成为
oauth2ResourceServer()
配置的候选者。

© www.soinside.com 2019 - 2024. All rights reserved.