Skip to content

Commit fc06373

Browse files
committed
perf:SpringCloudGateway之统一鉴权篇与SpringCloudGateway之统一鉴权篇补充
1 parent 9c527d1 commit fc06373

File tree

2 files changed

+388
-2
lines changed

2 files changed

+388
-2
lines changed
Lines changed: 318 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,318 @@
1-
# SpringCloudGateway之统一鉴权篇
1+
# SpringCloudGateway之统一鉴权篇
2+
## SpringCloudGateway实现统一鉴权的方式
3+
### 基于JWT(JSON Web Token)
4+
>在客户端登录成功后,服务端生成一个包含用户信息和过期时间等数据的JWT令牌返回给客户端。
5+
客户端在后续请求中将此令牌放在请求头(如Authorization: Bearer token)中发送给网关。
6+
网关层通过自定义的GatewayFilter Factory来拦截所有请求,并检查请求头中的JWT令牌,使用对应的解码器对其进行解密和校验,包括但不限于签名验证、过期时间检查等。
7+
8+
```java
9+
import org.springframework.cloud.gateway.filter.GatewayFilter;
10+
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
11+
import org.springframework.http.server.reactive.ServerHttpRequest;
12+
import org.springframework.stereotype.Component;
13+
import org.springframework.web.server.ServerWebExchange;
14+
import reactor.core.publisher.Mono;
15+
16+
@Component
17+
public class JwtAuthenticationGatewayFilterFactory extends AbstractGatewayFilterFactory<JwtAuthenticationGatewayFilterFactory.Config> {
18+
19+
@Override
20+
public GatewayFilter apply(Config config) {
21+
return (exchange, chain) -> {
22+
ServerHttpRequest request = exchange.getRequest();
23+
String jwtToken = getTokenFromRequest(request);
24+
25+
// 假设我们有一个JwtService类来处理验证逻辑
26+
JwtService jwtService = new JwtService();
27+
if (jwtService.isTokenValid(jwtToken)) {
28+
return chain.filter(exchange);
29+
} else {
30+
return unauthorizedResponse(exchange);
31+
}
32+
};
33+
}
34+
35+
private Mono<Void> unauthorizedResponse(ServerWebExchange exchange) {
36+
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
37+
return exchange.getResponse().setComplete();
38+
}
39+
40+
private String getTokenFromRequest(ServerHttpRequest request) {
41+
// 从请求头中获取JWT令牌
42+
return request.getHeaders().getFirst("Authorization").replace("Bearer ", "");
43+
}
44+
45+
// 配置类可选,根据需要添加配置参数
46+
public static class Config {
47+
// 示例配置项,实际应用可能不需要
48+
// private String headerName;
49+
// ...
50+
}
51+
}
52+
```
53+
- yaml配置
54+
```yaml
55+
spring:
56+
cloud:
57+
gateway:
58+
routes:
59+
- id: users-service-route
60+
uri: lb://users-service
61+
predicates:
62+
- Path=/api/users/**
63+
filters:
64+
- name: JwtAuthentication # 自定义过滤器名称
65+
# 如果有配置项,则可以在这里传入
66+
```
67+
68+
### 集成OAuth2授权服务器
69+
>Spring Cloud Gateway与OAuth2授权服务器(如Keycloak、Spring Authorization Server等)结合,处理OAuth2的访问令牌(Access Token)和刷新令牌(Refresh Token)的验证。
70+
当接收到带有令牌的请求时,网关可以调用授权服务器的/oauth/check_token端点或其他方式进行令牌的有效性验证。
71+
#### 配置Oauth2资源服务器:
72+
73+
首先需要有一个独立的OAuth2授权服务器,用于处理用户的登录、发放令牌(如JWT)等授权流程。
74+
在各个微服务应用中配置自己为Oauth2资源服务器,通过spring-security-oauth2-resource-server模块来保护资源,并验证从Gateway传递过来的访问令牌的有效性。
75+
#### 配置Spring Cloud Gateway:
76+
77+
添加必要的依赖项,集成Spring Security与OAuth2客户端支持。
78+
在Gateway的配置文件中设置路由规则,指定哪些路由需要经过OAuth2的过滤器进行鉴权。
79+
配置OAuth2的客户端信息,以便向授权服务器请求令牌验证信息。
80+
使用spring-cloud-starter-gateway 和 spring-security-oauth2-client 等相关依赖并配置Gateway路由过滤器,例如添加 OAuth2AuthorizationCodeGrantFilter 或 OAuth2LoginFilter 用于处理用户身份认证。
81+
#### 路由规则及鉴权过滤器:
82+
83+
定义路由规则,比如:
84+
85+
```yaml
86+
87+
gateway:
88+
routes:
89+
- id: oauth2-api-route
90+
uri: lb://your-microservice-name # 路由到的实际服务地址
91+
predicates:
92+
- Path=/api/** # 匹配特定路径的请求
93+
filters:
94+
- name: OAuth2Authorization Bearer Token Relay # 或者其他适合的过滤器名称,用于转发令牌到下游服务
95+
```
96+
97+
#### 令牌验证与权限控制:
98+
当请求到达Gateway时,带有OAuth2令牌的请求将被特定的过滤器拦截,过滤器会验证令牌的有效性。
99+
如果令牌有效,则允许请求继续通过Gateway路由至相应的微服务;如果无效,则返回未授权错误。
100+
101+
### 基于API Gateway层面的过滤器实现
102+
>创建自定义的GatewayFilter Factory,根据需要设计并实现自己的鉴权逻辑,比如检查请求头中的特定字段、查询参数或Cookie等。
103+
如果是微服务架构,还可以利用服务间通信机制,向认证服务发起请求以进行用户身份和权限的验证。
104+
- 创建自定义过滤器
105+
> 创建一个继承org.springframework.cloud.gateway.filter.GatewayFilter或实现org.springframework.cloud.gateway.filter.factory.GatewayFilterFactory的类,并在其内部实现鉴权逻辑。
106+
107+
```java
108+
import org.springframework.cloud.gateway.filter.GatewayFilter;
109+
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
110+
import org.springframework.core.Ordered;
111+
import org.springframework.http.server.reactive.ServerHttpRequest;
112+
import org.springframework.http.server.reactive.ServerHttpResponse;
113+
import org.springframework.stereotype.Component;
114+
import reactor.core.publisher.Mono;
115+
116+
@Component
117+
public class CustomAuthorizationFilter implements GatewayFilter, Ordered {
118+
119+
@Override
120+
public Mono<Void> filter(ServerHttpRequest request, ServerHttpResponse response, GatewayFilterChain chain) {
121+
// 从请求头或其他位置获取Token信息
122+
String token = getTokenFromRequest(request);
123+
124+
// 验证Token有效性(这里只是一个示例,实际验证逻辑需要根据OAuth2服务器的接口和规范进行)
125+
if (isValidToken(token)) {
126+
return chain.filter(request);
127+
} else {
128+
// Token无效时返回401 Unauthorized
129+
response.setStatusCode(HttpStatus.UNAUTHORIZED);
130+
return response.setComplete();
131+
}
132+
}
133+
134+
private boolean isValidToken(String token) {
135+
// 实现你的Token验证逻辑,可能需要向OAuth2授权服务器发送请求验证Token
136+
// ...
137+
return true; // 假设此处验证通过
138+
}
139+
140+
private String getTokenFromRequest(ServerHttpRequest request) {
141+
// 获取请求中的Token,比如从Authorization Header中提取Bearer Token
142+
return request.getHeaders().getFirst("Authorization").replace("Bearer ", "");
143+
}
144+
145+
@Override
146+
public int getOrder() {
147+
// 设置过滤器执行顺序,可以根据需求调整
148+
return -100;
149+
}
150+
}
151+
```
152+
- 注册过滤器到路由规则
153+
154+
```yaml
155+
spring:
156+
cloud:
157+
gateway:
158+
routes:
159+
- id: secured_route
160+
uri: lb://your-service-id
161+
predicates:
162+
- Path=/secured/**
163+
filters:
164+
- name: CustomAuthorizationFilter
165+
```
166+
167+
### 配合Spring Security OAuth2
168+
>将Spring Security OAuth2与Spring Cloud Gateway整合,配置OAuth2资源服务器支持,使得网关可以直接处理已验证过的请求,或者在转发请求前进行进一步的权限验证。
169+
170+
```java
171+
首先,需要在pom.xml文件中添加以下依赖:
172+
xml
173+
<dependency>
174+
<groupId>org.springframework.cloud</groupId>
175+
<artifactId>spring-cloud-starter-gateway</artifactId>
176+
</dependency>
177+
178+
<dependency>
179+
<groupId>org.springframework.security</groupId>
180+
<artifactId>spring-security-oauth2-client</artifactId>
181+
</dependency>
182+
在application.yml文件中,配置OAuth2客户端的相关信息:
183+
yaml
184+
spring:
185+
cloud:
186+
gateway:
187+
routes:
188+
- id: my_route
189+
uri: http://localhost:8081
190+
predicates:
191+
- Path=/api/**
192+
filters:
193+
- OAuth2ClientAuthenticationProcessingFilter
194+
195+
spring:
196+
security:
197+
oauth2:
198+
client:
199+
registration:
200+
my_client:
201+
client-id: 123456
202+
client-secret: abcdef
203+
authorization-grant-type: authorization_code
204+
redirect-uri: http://localhost:8080/login/oauth2/code/my_client
205+
scope: read,write
206+
provider:
207+
my_provider:
208+
authorization-endpoint: http://localhost:8089/oauth2/authorize
209+
token-endpoint: http://localhost:8089/oauth2/token
210+
user-info-endpoint: http://localhost:8089/me
211+
在代码中,实现OAuth2客户端的相关逻辑:
212+
java
213+
@Configuration
214+
public class GatewayConfig {
215+
216+
@Bean
217+
public RouterFunction<ServerResponse> route(OAuth2ClientAuthenticationProcessingFilter oauth2Filter) {
218+
return RouterFunctions
219+
.route(RequestPredicates.path("/api/**"), request -> {
220+
request.mutate().header(HttpHeaders.AUTHORIZATION, "Bearer " + getAccessToken(oauth2Filter))
221+
.build();
222+
return forward(request);
223+
});
224+
}
225+
226+
private String getAccessToken(OAuth2ClientAuthenticationProcessingFilter oauth2Filter) {
227+
// 获取access token的逻辑
228+
// ...
229+
}
230+
231+
private ServerResponse forward(ServerRequest request) {
232+
// 路由转发的逻辑
233+
// ...
234+
}
235+
}
236+
```
237+
238+
### 基于Redis或数据库存储的Token验证
239+
>对于非JWT类型的Token,可以在Redis或数据库中存储已签发的Token及其相关信息,在网关层从请求中提取Token并对比存储的信息进行有效性验证。
240+
#### 添加依赖
241+
确保项目包含了Spring Cloud Gateway、Spring Security、OAuth2以及Spring Data Redis相关依赖。
242+
```xml
243+
<dependencies>
244+
<!-- Spring Cloud Gateway -->
245+
<dependency>
246+
<groupId>org.springframework.cloud</groupId>
247+
<artifactId>spring-cloud-starter-gateway</artifactId>
248+
</dependency>
249+
250+
<!-- Spring Security & OAuth2 -->
251+
<dependency>
252+
<groupId>org.springframework.boot</groupId>
253+
<artifactId>spring-boot-starter-security</artifactId>
254+
</dependency>
255+
<dependency>
256+
<groupId>org.springframework.security.oauth.boot</groupId>
257+
<artifactId>spring-security-oauth2-resource-server</artifactId>
258+
</dependency>
259+
260+
<!-- Spring Data Redis -->
261+
<dependency>
262+
<groupId>org.springframework.boot</groupId>
263+
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
264+
</dependency>
265+
</dependencies>
266+
```
267+
#### 配置Redis Token Store
268+
> 配置Spring Security使用Redis存储和检索JWT或其他类型Token的信息:
269+
```yaml
270+
spring:
271+
security:
272+
oauth2:
273+
resourceserver:
274+
jwt:
275+
jwk-set-uri: http://your-oauth2-server.com/jwks # 如果是JWT,则配置公钥库地址
276+
issuer-uri: http://your-oauth2-server.com # JWT发行者地址
277+
oauth2:
278+
client:
279+
registration:
280+
your-client:
281+
# ... 客户端注册信息 ...
282+
provider:
283+
your-provider:
284+
# ... 授权服务器信息 ...
285+
resource:
286+
token-info-uri: http://your-oauth2-server.com/check_token # 可选,如果使用服务端校验Token(非JWT)
287+
redis:
288+
token-store: true # 开启Redis作为Token存储
289+
290+
data:
291+
redis:
292+
port: 6379
293+
host: localhost
294+
```
295+
#### 配置路由与过滤器
296+
通过Gateway的路由规则指定哪些请求需要经过OAuth2认证,并使用内置或自定义过滤器处理Token验证。
297+
298+
```yaml
299+
spring:
300+
cloud:
301+
gateway:
302+
routes:
303+
- id: secured_route
304+
uri: lb://your-service-id
305+
predicates:
306+
- Path=/secured/**
307+
filters:
308+
- name: BearerTokenAuthenticationFilter
309+
args:
310+
# ... 过滤器参数 ...
311+
312+
313+
```
314+
#### 安全配置
315+
启用资源服务器模式并配置从Redis读取Token信息的逻辑。
316+
317+
### RBAC(Role-Based Access Control)权限控制
318+
>结合角色权限模型,在验证Token有效的同时,检查当前请求路径所要求的角色权限是否与用户持有的Token中声明的角色匹配。
Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,70 @@
1-
# SpringCloudGateway之限流集成篇
1+
# SpringCloudGateway之限流集成篇
2+
>在Spring Cloud Gateway中实现限流(Rate Limiting)可以通过集成Spring Cloud Gateway的熔断和限流功能以及第三方限流组件如Sentinel或Resilience4j。
3+
4+
## SpringCloudGateway与Sentinel组件集成
5+
### 添加依赖
6+
7+
```xml
8+
首先确保项目包含Spring Cloud Gateway和Sentinel相关依赖。
9+
<dependencies>
10+
<dependency>
11+
<groupId>org.springframework.cloud</groupId>
12+
<artifactId>spring-cloud-starter-gateway</artifactId>
13+
</dependency>
14+
<!-- Sentinel Spring Cloud Gateway Adapter -->
15+
<dependency>
16+
<groupId>com.alibaba.csp</groupId>
17+
<artifactId>sentinel-adapter-spring-cloud-gateway-2.x</artifactId>
18+
<version>{sentinel-version}</version>
19+
</dependency>
20+
<!-- Sentinel Core -->
21+
<dependency>
22+
<groupId>com.alibaba.csp</groupId>
23+
<artifactId>sentinel-core</artifactId>
24+
<version>{sentinel-version}</version>
25+
</dependency>
26+
</dependencies>
27+
```
28+
### 配置Sentinel
29+
> 在application.yml或application.properties文件中配置Sentinel的相关参数
30+
31+
```yaml
32+
spring:
33+
cloud:
34+
sentinel:
35+
transport:
36+
dashboard: localhost:8080 # Sentinel控制台地址
37+
port: 8719 # Sentinel与控制台之间的通讯端口
38+
filter:
39+
url-patterns: "/api/**" # 需要进行限流处理的路由路径
40+
```
41+
42+
### 启用Sentinel Gateway适配器
43+
>创建一个配置类以启用Sentinel适配器,并注册到Spring容器中
44+
45+
```java
46+
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
47+
import com.alibaba.csp.sentinel.adapter.gateway.sc.config.SentinelGatewayConfig;
48+
import org.springframework.cloud.gateway.filter.GlobalFilter;
49+
import org.springframework.context.annotation.Bean;
50+
import org.springframework.context.annotation.Configuration;
51+
52+
@Configuration
53+
public class SentinelGatewayConfiguration {
54+
55+
@Bean
56+
public GlobalFilter sentinelGatewayFilter() {
57+
return new SentinelGatewayFilter();
58+
}
59+
60+
@Bean
61+
public SentinelGatewayConfig sentinelGatewayConfig() {
62+
return new SentinelGatewayConfig();
63+
}
64+
}
65+
```
66+
### 配置限流规则
67+
>通过Sentinel控制台或API动态添加限流规则,包括QPS限制、热点限流等策略
68+
>为/api/user路由设置QPS限流
69+
为/api/user路由设置QPS限流
70+
在Sentinel控制台上新建一个限流规则,资源名可以是/api/user,然后设置每秒允许的请求次数。

0 commit comments

Comments
 (0)