是否有任何手动参考或方法可以在 Spring Cloud 中的 API 网关上应用安全性?我已经使用 Spring Cloud 构建了一个网关并添加了路由,现在我需要添加安全性,在请求到达端点之前使用 Auth Server (WSO2 Identity Server) 验证请求。我想知道是否有办法让我的 API 网关联系身份验证服务器(WSO2 身份服务器)来验证请求?必须如何进行配置?
我正在尝试做的是构建一个 API 网关,它使用 WSO2 身份服务器处理路由和安全性,因此任何知识、参考或最佳实践共享来处理 API 网关中的安全性都可以提供帮助。
请在下面找到我为 API 网关编写的代码:
1- 春季启动依赖
'org.springframework.cloud:spring-cloud-starter-circuitbreaker-resilience4j'
'org.springframework.cloud:spring-cloud-starter-gateway'
'org.springframework.boot:spring-boot-starter-test'
'org.springframework.cloud:spring-cloud-starter-contract-stub-runner'
'org.springframework.boot:spring-boot-starter-security'
'org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.1.1.RELEASE'
'org.springframework.boot:spring-boot-starter-web'
2- 路由配置(application.yml)
春天:
主要的:
web-application-type: reactive
allow-bean-definition-overriding: true
配置:
import: ''
云:
gateway:
routes:
- id: demo-ms1
uri: http://localhost:8081/
predicates:
- Path=/api/demo1
- id: demo-ms2
uri: http://localhost:8082/
predicates:
- Path=/api/demo2/**
3- WSO2 (application.yml) 的安全配置
安全:
oauth2:
resource:
user-info-uri: https://localhost:9443/oauth2/userinfo
token-info-uri: https://localhost:9443/oauth2/introspect
filter-order: '3'
prefer-token-info: 'true'
client:
client-secret: admin
client-id: admin
user-authorization-uri: https://localhost:9443/oauth2/token/authorize
access-token-uri: https://localhost:9443/oauth2/token
scope: openid
4-资源服务器配置类
package com.gateway.demoGateway.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher;
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter{
@Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatcher(new RequestHeaderRequestMatcher("Authorization"))
.authorizeRequests().anyRequest().fullyAuthenticated();
}
}
5- Spring Boot 主应用类
@SpringBootApplication
@EnableOAuth2Sso
@EnableWebSecurity
public class DemoGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(DemoGatewayApplication.class, args);
}
}