springcloud-Finchley学习笔记-gateway网关自定义过滤器

创建过滤器代码:验证令牌过滤不完整版本

/**
 * 令牌验证过滤器
 * @author wuxie
 * @date 2019-1-14
 */
public class TokenValidateGatewayFilterFactory extends AbstractGatewayFilterFactory<TokenValidateGatewayFilterFactory.Config> {

    private static Logger logger= LoggerFactory.getLogger(TokenValidateGatewayFilterFactory.class);

    private final JsonMapper jsonMapper;

    public TokenValidateGatewayFilterFactory(JsonMapper jsonMapper) {
        super(Config.class);
        this.jsonMapper = jsonMapper;
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            logger.info("TokenValidateGatewayFilterFactory...");
            String token = exchange.getRequest().getHeaders().getFirst("Authorization");
            //校验token的合法性
            boolean tokenValidated= true;
            if (tokenValidated) {
                // 令牌合法,继续访问,可以进行一些处理,如:添加头信息,参数等
                ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
                //比如,根据令牌获得用户信息,userId
                builder.header("ch-userId", Base64Utils.encodeFromString("用户Id"));
                return chain.filter(exchange.mutate().request(builder.build()).build());
            }
            //令牌不合法
            ServerHttpResponse response = exchange.getResponse();
            //设置headers
            HttpHeaders httpHeaders = response.getHeaders();
            httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
            httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
            //过滤器中跨域需要自己处理
            //设置body
            ResultEntity<String> resultEntity = ResultEntityBuilder.fail("没有访问权限");
            String resultStr = jsonMapper.toString(resultEntity,true);
            DataBuffer bodyDataBuffer = response.bufferFactory().wrap(resultStr.getBytes());

            return response.writeWith(Mono.just(bodyDataBuffer));
        };
    }

    public static class Config{

    }
}

将过滤器注册成Bean对象

/**
 * 应用配置
 * @author wuxie
 * @date 2019-1-14
 */
@Configuration
public class AppConfig {

    @Bean
    public TokenValidateGatewayFilterFactory tokenValidateGatewayFilterFactory(JsonMapper jsonMapper){
        return new TokenValidateGatewayFilterFactory(jsonMapper);
    }
}

配置gateway配置:只需要配置过滤类的前缀即可

spring:
  cloud:
    gateway:
      default-filters:
        - TokenValidate

此处是配置是全局过滤器了,也可以直接配置到某个路由上。

你可能感兴趣的:(SpringCloud,springboot)