我正在尝试使用具有spring安全性的spring云网关,并尝试通过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();
}
我从angular调用这个API,但我在飞行前请求中得到了CORS错误。我什么都试过了,但不知道哪里出了错。知道吗?
我通过将Angular App移到API网关后面来解决这个问题,并在API网关和微服务中添加了以下代码
在API网关中
http.cors();
在微服务中
@Configuration
@EnableWebMvc
public class RestServiceCorsApplication implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
将HttpMethod.OPTIONS添加到允许的方法中。使用OPTIONS方法发送到服务器的飞行前请求。所以你的配置应该像下面这样:
allowedMethods:
- GET
- POST
- DELETE
- PUT
- OPTIONS
此外,您的路由必须包含OPTIONS方法。例如:
spring.cloud.gateway.routes[0].predicates[1] = Method=GET,POST,OPTIONS