添加gateway依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
创建一个tokenFilter
实现全局过滤器GlobalFilter,并且实现fitler方法
@Value("${cn.token.key}")
private String tokenKey;
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpResponse response = exchange.getResponse();
List<String> tokens = exchange.getRequest().getHeaders().get("token");
if(ObjectUtil.isEmpty(tokens)){
log.debug("请传输token");
response.setStatusCode(HttpStatus.PAYMENT_REQUIRED);
return response.setComplete();
}
String token = tokens.get(0);
if(ObjectUtil.isEmpty(token)){
log.debug("token不能为空");
response.setStatusCode(HttpStatus.PAYMENT_REQUIRED);
return response.setComplete();
}
boolean b = false;
try {
//利用jwt对token进行验证
JWTValidator.of(token).validateAlgorithm(JWTSignerUtil.hs256(tokenKey.getBytes())).validateDate();
b = true;
}catch (Exception ex){
ex.printStackTrace();
log.error("token不正确");
}
if(!b){
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return response.setComplete();
}
return chain.filter(exchange);
}