说说背景:假若有一个用户服在用户登陆后,生成一个token给到客户端,用户每次请求时都须要这个token,因而每次都会在网关 gateway 校验,校验经过后网关从token中解析出userId,而后将userId送到各个服务。php
好比如今有一个 java 服务 和 一个 php 服务,从网关访问的URL 分别是 http://127.0.0.1:8201/java/ 和 http://127.0.0.1:8201/php/,如今暂时只需对 php 这个服务验证,先看效果图html
spring cloud gateway 的官网文档地址:http://cloud.spring.io/spring-cloud-gateway/single/spring-cloud-gateway.html#_addrequestheader_gatewayfilter_factoryjava
1、须要自定义 GatewayFilterFactory 继承 AbstractGatewayFilterFactory 抽象类,代码以下:react
package cn.taxiong.tx_api_gateway_server.filter; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.http.HttpHeaders; import org.springframework.http.server.reactive.ServerHttpResponse; import reactor.core.publisher.Mono; /** * JWT验证的过滤器 * * @author szliugx@gmail.com * @create 2018-09-09 下午10:05 **/ public class JwtCheckGatewayFilterFactory extends AbstractGatewayFilterFactory<JwtCheckGatewayFilterFactory.Config> { public JwtCheckGatewayFilterFactory() { super(Config.class); } @Override public GatewayFilter apply(Config config) { return (exchange, chain) -> { String jwtToken = exchange.getRequest().getHeaders().getFirst("Authorization"); //校验jwtToken的合法性 if (jwtToken != null) { // 合法 // 将用户id做为参数传递下去 return chain.filter(exchange); } //不合法(响应未登陆的异常) 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 String warningStr = "未登陆或登陆超时"; DataBuffer bodyDataBuffer = response.bufferFactory().wrap(warningStr.getBytes()); return response.writeWith(Mono.just(bodyDataBuffer)); }; } public static class Config { //Put the configuration properties for your filter here } }
2、须要将自定义的 GatewayFilterFactory 注入到Spring 中spring
package cn.taxiong.tx_api_gateway_server.config; import cn.taxiong.tx_api_gateway_server.filter.JwtCheckGatewayFilterFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 应用配置 * * @author szliugx@gmail.com * @create 2018-09-09 下午10:57 **/ @Configuration public class AppConfig { @Bean public JwtCheckGatewayFilterFactory jwtCheckGatewayFilterFactory(){ return new JwtCheckGatewayFilterFactory(); } }
3、网关服务的配置文件中配置 自定义过滤器 生效的服务json
这里只配置了 php 这个服务,java 这个服务不使用这个过滤器规则api