背景
我正在创建一个基于微服务的项目。前端使用 Angular 15
,后端使用 Spring 3.0.2
。认证方面,我使用了 Keycloack 20.0.3
来为前后端提供身份验证。我的多个微服务运行在不同的 Spring 项目中。我使用 Spring Cloud Gateway
作为前端的入口,这样就不需要在 Angular 中管理端口号。同时,我还使用了 Eureka
作为网关。
注意:我的网关仅使用 YAML 文件进行配置,没有使用
Spring Security
或Keycloak
进行配置。CORS 被禁用。
spring:
application:
name: gateway
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "https://localhost:4200"
allowedMethods: "*"
allowedHeaders: "*"
routes:
- id: users
uri: lb://micro-service-1/api/users
predicates:
- Method=GET,POST,PUT,DELETE
- Path=/api/users/**
- id: assets
uri: lb://micro-service-2/api/assets
predicates:
- Method=GET,POST,PUT,DELETE
- Path=/api/assets/**
server:
port: 8100
eureka:
client:
registerWithEureka: true
serviceUrl:
defaultZone: http://localhost:8761/eureka
我的问题
我正在构建一个BREAD API(浏览,读取,编辑,添加,删除)。浏览和读取(通常使用Http GET请求)工作正常,但其他操作在Angular
中会抛出403错误。
注意:我尝试使用Postman进行测试,但没有抛出错误。
当我尝试跳过网关直接与微服务通信时,一切都正常,没有错误。
注意:我的后端只是RESTful APIs,Keycloak Auth处理所有的登录/注销/注册...
我的失败解决方案
我的网关未配置Spring Security
或Keycloak
,CORS已禁用。
1. 尝试在网关上禁用CSRF
security.enable-csrf: false
它没有起作用!
2. 尝试在网关上添加Spring Security
并禁用CSRF
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf().disable().cors().disable().httpBasic().disable()
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
return http.build();
}
仍需要凭据并与 Keycloak
冲突
3. 尝试为网关配置 Keycloak
Keycloak
需要 Spring Web
,导致与 Spring Cloud Gateway
冲突
我花了2周时间,在互联网上找不到任何有用的信息。一切都已经过时或根本无法使用。有什么线索吗?
注意:我知道可以使用 Angular Proxy Config 替换网关,但这会破坏 Spring Cloud 架构,并且只是开发目的的解决方法。