SpringCloud搭建微服务之Gateway+Jwt实现统一鉴权
以下是一个简化的Spring Cloud Gateway配合JWT实现鉴权的示例:
- 添加依赖(pom.xml):
<dependencies>
<!-- Spring Cloud Gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- Spring Cloud Gateway Filter for JWT -->
<dependency>
<groupId>com.marcosbarbero.cloud</groupId>
<artifactId>spring-cloud-gateway-core-filter-jwt-rewrite</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
</dependencies>
- 配置文件(application.yml):
spring:
cloud:
gateway:
routes:
- id: service-id
uri: http://localhost:8080
predicates:
- Path=/service/**
filters:
- StripPrefix=1
- name: JwtRequestWrapperFilter
- name: JwtDecodeFilter
args:
public-key: "your_public_key"
token-is-optional: false
- 配置JWT过滤器(FilterConfig.java):
@Configuration
public class FilterConfig {
@Bean
public JwtFilter jwtFilter() {
return new JwtFilter("your_public_key");
}
}
- JWT过滤器实现(JwtFilter.java):
public class JwtFilter implements GatewayFilter, Ordered {
private String publicKey;
public JwtFilter(String publicKey) {
this.publicKey = publicKey;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String token = exchange.getRequest().getHeaders().getFi
评论已关闭