在 Spring Cloud Gateway 中实现 JWT 鉴权是一种常见的做法,用于在微服务架构中保护路由并确保安全。JWT(JSON Web Token)是一种用于在网络应用环境中传递声明的开放标准。下面是一个使用 Spring Cloud Gateway 和 JWT 实现网关鉴权的详细指南。
1. 创建 Spring Cloud Gateway 项目
首先,创建一个 Spring Boot 项目,并引入 Spring Cloud Gateway 依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
2. 实现 JWT 过滤器
创建一个自定义的过滤器,用于解析 JWT 并验证其有效性。
JwtAuthenticationFilter.java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.web.server.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import javax.annotation.PostConstruct;
import java.util.List;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Value("${jwt.secret}")
private String jwtSecret;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
String authHeader = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
return chain.filter(exchange);
}
String token = authHeader.substring(7);
try {
Claims claims = Jwts.parser()
.setSigningKey(jwtSecret.getBytes())
.parseClaimsJws(token)
.getBody();
// You can set user details in the security context here if needed
// For simplicity, we're just logging the claims here
System.out.println("Claims: " + claims);
return chain.filter(exchange);
} catch (SignatureException e) {
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return response.setComplete();
}
}
}
3. 配置 Gateway 过滤器
将 JWT 过滤器配置到 Gateway 的过滤链中。
GatewayConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.factory.RewritePathGatewayFilterFactory;
import org.springframework.web.reactive.config.CorsRegistry;
import org.springframework.web.reactive.config.WebFluxConfigurer;
@Configuration
public class GatewayConfig implements WebFluxConfigurer {
@Bean
public GlobalFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}
// Other configurations, like route definitions
}
4. 配置 Spring Security
配置 Spring Security 来使用 JWT 鉴权,并设置相关的安全策略。
SecurityConfig.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.annotation.web.reactive.WebFluxSecurityConfiguration;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.authentication.ServerHttpBasicAuthenticationConverter;
import reactor.core.publisher.Mono;
@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {
@Autowired
private JwtAuthenticationFilter jwtAuthenticationFilter;
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
http
.csrf().disable()
.authorizeExchange()
.pathMatchers("/public/**").permitAll()
.anyExchange().authenticated()
.and()
.addFilterBefore(jwtAuthenticationFilter, SecurityWebFiltersOrder.AUTHENTICATION);
return http.build();
}
}
5. 配置 JWT 密钥和其他设置
application.yml
server:
port: 8080
jwt:
secret: your-secret-key
6. 生成和验证 JWT
为了使用 JWT,你需要生成 JWT 并在登录或认证过程中提供它。下面是一个简单的生成 JWT 的示例方法:
JwtUtil.java
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
public class JwtUtil {
private String secretKey = "your-secret-key";
public String generateToken(String username) {
return Jwts.builder()
.setSubject(username)
.setExpiration(new Date(System.currentTimeMillis() + 864_000_000)) // 10 days
.signWith(SignatureAlgorithm.HS256, secretKey.getBytes())
.compact();
}
}
7. 测试和验证
1. **启动 Gateway 服务**,确保配置和过滤器正常运行。
2. **生成 JWT**,可以通过其他服务(如认证服务)生成 JWT。
3. **请求 Gateway**,在请求头中添加 `Authorization: Bearer <your-jwt-token>`,确保 JWT 过滤器能够成功处理和验证请求。
总结
1. **创建 Spring Cloud Gateway 项目**:设置基本的项目依赖和配置。
2. **实现 JWT 过滤器**:自定义 JWT 过滤器以处理 JWT 验证。
3. **配置 Gateway 过滤器**:将 JWT 过滤器配置到 Gateway 的过滤链中。
4. **配置 Spring Security**:配置 Spring Security 以与 JWT 过滤器一起使用。
5. **设置 JWT 密钥和其他配置**:在 `application.yml` 中配置 JWT 相关的密钥和设置。
6. **生成和验证 JWT**:实现 JWT 生成和验证的逻辑,并进行测试。