Spring Cloud Gateway 4.2.1 Spring Authorization Server 1.4.2
时间: 2025-05-22 07:36:27 浏览: 19
### Spring Cloud Gateway 4.2.1与Spring Authorization Server 1.4.2的集成
在现代微服务架构中,Spring Cloud Gateway 和 Spring Authorization Server 的组合是一种常见的解决方案,用于实现 API 网关的安全性和授权管理。以下是关于如何在 Spring Cloud Gateway 中集成和使用 Spring Authorization Server 的详细说明。
#### 配置依赖项
首先,在项目的 `pom.xml` 文件中引入必要的依赖项:
```xml
<dependencies>
<!-- Spring Cloud Gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>4.2.1</version>
</dependency>
<!-- Spring Authorization Server -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-authorization-server</artifactId>
<version>1.4.2</version>
</dependency>
<!-- 其他必要依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
```
以上配置确保项目能够支持 Spring Cloud Gateway 和 Spring Authorization Server 的功能[^5]。
---
#### 设置 OAuth2 授权服务器
创建一个自定义的 `AuthorizationServerConfig` 类来配置 OAuth2 授权服务器的功能:
```java
@Configuration(proxyBeanMethods = false)
public class AuthorizationServerConfig {
@Autowired
private DataSource dataSource;
@Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("gateway-client")
.clientSecret("{noop}secret") // 使用明文密码 (仅限测试环境)
.scope(OidcScopes.OPENID, OidcScopes.PROFILE)
.redirectUri("http://localhost:8080/login/oauth2/code/gateway-client")
.tokenSettings(TokenSettings.builder()
.accessTokenTimeToLive(Duration.ofHours(1))
.refreshTokenTimeToLive(Duration.ofDays(7)).build())
.build();
return new InMemoryRegisteredClientRepository(registeredClient);
}
@Bean
public JdbcOAuth2AuthorizationService authorizationService(ConnectionFactory connectionFactory) {
return new JdbcOAuth2AuthorizationService(connectionFactory);
}
}
```
此代码片段展示了如何注册客户端并设置令牌的有效期和其他参数[^6]。
---
#### 安全过滤器链配置
为了让 Spring Cloud Gateway 能够验证来自用户的请求,需要为其配置安全上下文。可以通过扩展 `WebSecurityConfigurerAdapter` 来完成这一点:
```java
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http,
ReactiveAuthenticationManager authenticationManager,
Converter<Jwt, ? extends AbstractAuthenticationToken> jwtAuthConverter) {
http.authorizeExchange(exchanges -> exchanges
.pathMatchers("/actuator/health").permitAll()
.anyExchange().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.authenticationManagerResolver(
exchange -> Mono.just(authenticationManager))));
return http.build();
}
@Bean
public JwtDecoder jwtDecoder() {
NimbusJwtDecoder decoder = NimbusJwtDecoder.withJwkSetUri("https://example.com/.well-known/jwks.json").build();
decoder.setClaimSetConverter(new CustomClaimsConverter());
return decoder;
}
}
```
在此配置中,路径 `/actuator/health` 对所有人开放,而其他所有路径都需要经过身份验证[^7]。
---
#### 自定义 JWT 解码逻辑
如果需要对 JWT 进行额外处理,则可以提供一个自定义解码器:
```java
@Component
public class CustomClaimsConverter implements Converter<Map<String, Object>, Map<String, Object>> {
@Override
public Map<String, Object> convert(Map<String, Object> claims) {
// 添加自定义逻辑以解析或修改 Claims 数据
return claims;
}
}
```
这一步允许开发者根据业务需求调整默认的行为[^8]。
---
#### 测试网关与授权服务器交互
启动应用程序后,可以通过 Postman 或 cURL 工具发送以下请求获取访问令牌:
```bash
curl --location 'http://localhost:9000/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'client_id=gateway-client' \
--data-urlencode 'client_secret=secret'
```
成功响应应返回类似于以下结构的内容:
```json
{
"access_token": "eyJhbGciOiJIUzI...",
"expires_in": 3600,
"token_type": "Bearer"
}
```
随后可将该 token 放入 HTTP 请求头中调用受保护资源:
```bash
curl -H "Authorization: Bearer eyJhbG..." http://localhost:8080/api/resource
```
---
### 总结
通过上述步骤,可以在 Spring Cloud Gateway 中无缝集成本地运行的 Spring Authorization Server 实现完整的 OAuth2 认证机制。这种设计不仅增强了系统的安全性,还提供了灵活的身份验证选项以满足不同场景下的需求[^9]。
阅读全文
相关推荐














