1. 程式人生 > >SpringCloud初體驗:七、gateway 網關服務如何做token驗證

SpringCloud初體驗:七、gateway 網關服務如何做token驗證

.get 效果圖 stat mage null framework pack cati 用戶登錄

說說背景:假如有一個用戶服在用戶登錄後,生成一個token給到客戶端,用戶每次請求時都需要這個token,於是每次都會在網關 gateway 校驗,校驗通過後網關從token中解析出userId,然後將userId送到各個服務。

比如現在有一個 java 服務 和 一個 php 服務,從網關訪問的URL 分別是 http://127.0.0.1:8201/java/ 和 http://127.0.0.1:8201/php/,現在暫時只需對 php 這個服務驗證,先看效果圖

技術分享圖片

spring cloud gateway 的官網文檔地址:http://cloud.spring.io/spring-cloud-gateway/single/spring-cloud-gateway.html#_addrequestheader_gatewayfilter_factory

一、需要自定義 GatewayFilterFactory 繼承 AbstractGatewayFilterFactory 抽象類,代碼如下:

技術分享圖片
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 [email protected] * @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 } }
View Code

二、需要將自定義的 GatewayFilterFactory 註入到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 [email protected]
 * @create 2018-09-09 下午10:57
 **/
@Configuration
public class AppConfig {
    @Bean
    public JwtCheckGatewayFilterFactory jwtCheckGatewayFilterFactory(){
        return new JwtCheckGatewayFilterFactory();
    }
}

三、網關服務的配置文件中配置 自定義過濾器 生效的服務

技術分享圖片

這裏只配置了 php 這個服務,java 這個服務不使用這個過濾器規則

SpringCloud初體驗:七、gateway 網關服務如何做token驗證