springcloudgateway集成springsecurity
时间: 2025-03-04 12:19:49 浏览: 28
集成 Spring Cloud Gateway 和 Spring Security
为了实现安全网关配置,在 Spring Boot 项目中集成 Spring Cloud Gateway 和 Spring Security 是一种常见做法。这不仅能够保护 API 路由的安全性,还能提供统一的身份验证和授权机制。
添加依赖项
首先,在 pom.xml
文件中添加必要的 Maven 依赖来引入 Spring Cloud Gateway 和 Spring Security:
<dependencies>
<!-- Spring Cloud Gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
</dependencies>
上述代码片段展示了如何通过 Maven 来管理项目的依赖关系并导入所需的库文件[^1]。
安全配置类定义
创建一个新的 Java 类用于自定义安全策略,该类需继承 WebSecurityConfigurerAdapter
或者采用基于函数的方式进行更简洁的设置。这里推荐使用最新的方式——即不继承任何基类而是直接利用 lambda 表达式的灵活性来进行配置:
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
return http
.authorizeExchange(exchanges -> exchanges
.pathMatchers("/actuator/**").permitAll() // 允许访问监控端点
.anyExchange().authenticated()) // 所有其他请求都需要认证
.oauth2ResourceServer(OAuth2ResourceServerSpec::jwt) // 使用 JWT 进行 OAuth2 认证
.build();
}
}
这段代码实现了对不同路径模式下的权限控制逻辑,并启用了 JSON Web Token (JWT) 的支持作为 OAuth2 协议的一部分。
应用属性调整
最后一步是在应用程序的主要配置文件 (application.yml
) 中指定一些额外参数以适应新的安全性需求:
spring:
cloud:
gateway:
routes:
- id: secured_api_route
uri: lb://SECURED-SERVICE
predicates:
- Path=/api/**
filters:
- StripPrefix=1
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://example.com/issuer
此部分设置了路由规则以及指定了颁发者的 URI 地址以便于解析传入令牌中的签名信息。
相关推荐


















