【发布时间】:2021-07-13 07:04:25
【问题描述】:
我正在尝试将 Spring Cloud Gateway 与 Spring Security 一起使用,并尝试通过 Angular 调用其余 API,但出现以下错误
Access to XMLHttpRequest at 'http://localhost:9090/api/v1/publishers/?pageNo=1&pageSize=10&sort=name,desc&sort=city,desc' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
根据文档https://cloud.spring.io/spring-cloud-gateway/multi/multi__cors_configuration.html
我必须在应用程序 yaml 文件中添加 globalcors。
这是我完整的 yaml 文件。
server:
port: 9090
keycloak-client:
server-url: http://keycloak-url:8080/auth
realm: dev
spring:
application:
name: gateway
security:
oauth2:
client:
provider:
keycloak:
issuer-uri: ${keycloak-client.server-url}/realms/${keycloak-client.realm}
user-name-attribute: preferred_username
registration:
keycloak:
client-id: cei-backend
client-secret: f4d3242b-1fee-4dab-a491-d91ac51d637f
cloud:
gateway:
default-filters:
- TokenRelay
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "http://localhost:4200"
allowedHeaders: "*"
allowedMethods:
- GET
- POST
- DELETE
- PUT
routes:
- id: publisher_route
uri: http://localhost:8000
predicates:
- Path=/api/v1/publishers/**
filters:
- RemoveRequestHeader=Cookie
logging:
level:
org.springframework.cloud.gateway: DEBUG
reactor.netty: DEBUG
以下是我的安全配置文件
@Configuration
public class SecurityConfig {
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http,
ReactiveClientRegistrationRepository clientRegistrationRepository) {
// Authenticate through configured OpenID Provider
http.oauth2Login();
// Also logout at the OpenID Connect provider
http.logout(logout -> logout.logoutSuccessHandler(new OidcClientInitiatedServerLogoutSuccessHandler(
clientRegistrationRepository)));
// Require authentication for all requests
http.authorizeExchange().anyExchange().authenticated();
// Allow showing /home within a frame
http.headers().frameOptions().mode(Mode.SAMEORIGIN);
// Disable CSRF in the gateway to prevent conflicts with proxied service CSRF
http.csrf().disable();
return http.build();
}
我正在从角度调用此 API,但我在预检请求中遇到了 CORS 错误。 我已经尝试了一切,但不知道我在哪里犯了错误。有什么想法吗?
【问题讨论】:
-
您的预检请求似乎被重定向并且未正确处理(您应该在问题中添加预检请求/响应以明确)。我想这是因为您需要对所有请求进行身份验证。我会说 OPTIONS 请求应该以某种方式列入白名单。
-
嗨@JanGaraj 我通过将 Angular 应用程序移动到 API 网关后面来解决它。谢谢
-
@user585014 你是如何将 Angular 移到 API 网关后面的?你有关于你的项目的 git 吗?
-
只需在您的 API 路由中添加一个新路由 - id:frontend_route uri:localhost:4200 谓词:- Path=/** 过滤器:- RemoveRequestHeader=Cookie,然后在您的安全配置 .pathMatchers 中添加以下内容("/portal/**").permitAll()
标签: angular spring-security keycloak spring-security-oauth2 spring-cloud-gateway