一 file-gateway/Tokenfilter
这个是定义了一个pring Cloud Gateway 应用中的全局过滤器
用于拦截请求并验证请求中的 JWT 令牌。
逐行注释下面的代码,一个token验证拦截器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| package top.quhailong.pan.file.gateway.filter; @Component @RefreshScope public class TokenFilter implements GlobalFilter, Ordered { @Value("${filter-url}") private String filterUrl; @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); String uri = request.getURI().getPath(); List<String> uriList = Arrays.asList(filterUrl.split(",")); for (String filterUrl:uriList) { if(uri.contains(filterUrl)){ return verifyToken(exchange, chain); } } return chain.filter(exchange); }
private Mono<Void> verifyToken(ServerWebExchange exchange, GatewayFilterChain chain) { try { ServerHttpRequest request; HttpCookie cookie = exchange.getRequest().getCookies().getFirst("token"); String token = cookie.getValue(); Claims claims = JWTUtils.parseJWT(token, "nimadetou".getBytes()); String subject = claims.getSubject(); UserInfoDTO userinfo = JSONUtils.parseObject(subject, UserInfoDTO.class); String operationInfo = URLEncoder.encode(JSONUtils.toJSONString(userinfo), StandardCharsets.UTF_8.toString()); request = exchange.getRequest().mutate().header("operationInfo", operationInfo).build(); return chain.filter(exchange.mutate().request(request).build()); } catch (Exception e) { ServerHttpResponse response = exchange.getResponse(); response.getHeaders().add("Content-Type", "application/json;charset=UTF-8"); DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(RestAPIResultDTO.Error("token验证失败")).getBytes()); return response.writeWith(Flux.just(dataBuffer)); } }
@Override public int getOrder() { return 0; } }
|
二 JWT
JWT(JSON Web Token)是一种用于在各方之间作为 JSON 对象安全传输信息的紧凑且自包含的方式。JWT 的使用场景包括身份验证、信息交换等。
(1)JWT结构
包含三个部分:Header(头部)、Payload(负载)、Signature(签名)
1
| Header.Payload.Signature
|
1. 头部
header通常包含两个部分,一个是令牌的类型(JWT)和签名算法(RSA,HMAC SH256)
1 2 3 4
| { "alg": "HS256", "typ": "JWT" }
|
2.Payload负载