說說背景:假若有一個用戶服在用戶登陸後,生成一個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