Spring Cloud Gateway 学习之全局过滤器,转发,添加头信息和JWT加解密

全局过滤,拦截前端的带来的token


@Component
public class TokenFilter implements GlobalFilter, Ordered {

    private static final Logger logger= LoggerFactory.getLogger( TokenFilter.class );
    @Override
    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        logger.info(" 前置 : " +exchange.getRequest().getBody() + "\t"+ exchange.getRequest().getURI().toString());
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        logger.info("token------->"+token);
        String token2 = JWTUtil.encrypt("mysecret");
      //是不能直接向 headers中放文件的
        // exchange.getRequest().getHeaders().add("inner-token", token2);
        //向headers中放文件,记得build
        ServerHttpRequest host = exchange.getRequest().mutate().header("inner-token", token2).build();
        //将现在的request 变成 change对象
        ServerWebExchange build = exchange.mutate().request(host).build();

       // logger.info("test port------->"+port);
        return chain.filter(build).then(Mono.fromRunnable(()->{
            logger.info(" 后置 : " +exchange.getResponse().getStatusCode() + "\t"+ exchange.getRequest().getURI().toString());
        }));
    }
   @Override
    public int getOrder() {
        return -100;
    }
}

 

转发请求到其他模块

@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) throws UnsupportedEncodingException {
   //@formatter:off

   //获取token认证,然后获取用户的角色和权限
   /*MyObject o = new MyObject();
   ArrayList list = new ArrayList<>();
   for (int i = 0; i <11 ; i++) {//12个都传不过去,~2.61kb
      list.add("SpringCloud 网关服务中添加网关请求头内容,有时候需要添加中文内容,这时候在业务服务获取的时候就出现了乱码,尝试了各种转码均无效,只有URLEncoder编码解码可以解决这个问题"+i);
   }*/
   String token = JWTUtil.encrypt("mysecret");
   System.out.println("token::==="+token);
   return builder.routes()
         .route("path_route", r -> r.path("/gateway/**")
               //.filters(f -> f.addRequestHeader("inner-token", token))
               .uri("http://localhost:8081"))
         .build();

}

JWT的加密解密

/**
 * 加密生成token
 * @return
 */
public static String encrypt (String secret) {
    try {

       // Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
//模拟数据
        ArrayList rolelist = new ArrayList<>();
        rolelist.add("Java开发");
        rolelist.add("模块设计");

        ArrayList permissionList = new ArrayList<>();
        permissionList.add("123"+Math.random());
        permissionList.add("456");
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create()
                .withClaim("roles", StringUtils.join(rolelist.toArray(), "|"))
                .withClaim("permissions",StringUtils.join(permissionList.toArray(), "|"))
               // .withExpiresAt(date)
                .sign(algorithm);
    } catch (Exception e) {
        log.error("error:{}", e);
        return null;
    }
}
/** * 
解密token 
* @return 
*/
public static boolean decrypt (String token, String secret) {
    try {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm)
                .build();
        DecodedJWT jwt = verifier.verify(token);
        //log.info("token is valid");       String roles = jwt.getClaim("roles").asString();
String permissions = jwt.getClaim("permissions").asString();
System.out.println(roles+"======"+"\n"+permissions);
        return true;
    } catch (Exception e) {
        log.info("token is invalid:{}", e.getMessage());
        return false;
    }
}

你可能感兴趣的:(spring_cloud)