首先在gateway的pom.xml文件下增加:
//hutool工具类 因为没传common类
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
// 热部署
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
在getway的config文件下生成LoginMemberFilter类(过滤器): 请求时带上token,返回时校验返回码是不是401
package com.jiawa.train.gateway.config; import com.jiawa.train.gateway.util.JwtUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; /** * 功能描述 * * @author ayyy * @date 2024/01/28 16:32 */ @Component public class LoginMemberFilter implements GlobalFilter , Ordered { private static final Logger LOG = LoggerFactory.getLogger(LoginMemberFilter.class); @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { String path = exchange.getRequest().getURI().getPath(); // 排除不需要拦截的请求 if (path.contains("/admin") || path.contains("/hello") || path.contains("/member/member/login") || path.contains("/member/member/send-code")){ LOG.info("不需要登录验证:{}",path); return chain.filter(exchange); }else { LOG.info("需要登录验证:{}",path); } // 获取header的token参数 String token = exchange.getRequest().getHeaders().getFirst("token"); LOG.info("会员登录验证开始,token:{}", token); if (token == null || token.isEmpty()){ LOG.info("token为空,请求被拦截"); // 设置成401错误 exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); // 中断请求 return exchange.getResponse().setComplete(); } // 校验token是否有效,包括token是否被改过,是否过期 boolean validate = JwtUtil.validate(token); if (validate){ LOG.info("token有效,放行该请求 "); return chain.filter(exchange); }else { LOG.info("token无效,请求被拦截"); // 设置成401错误 exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); // 中断请求 return exchange.getResponse().setComplete(); } } @Override public int getOrder() { return 0; } }
修改jwtUtil类:
public static boolean validate(String token) { LOG.info("开始JWT token校验,token:{}", token); GlobalBouncyCastleProvider.setUseBouncyCastle(false); try { JWT jwt = JWTUtil.parseToken(token).setKey(key.getBytes()); // validate包含了verify boolean validate = jwt.validate(0); LOG.info("JWT token校验结果:{}", validate); return validate; } catch (Exception e) { LOG.info("JWT token校验异常:{}", e); return false; } }