SpringCloud初体验:七、gateway 网关服务如何做token验证

说说背景:假如有一个用户服在用户登录后,生成一个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 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
    }
}
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 szliugx@gmail.com
 * @create 2018-09-09 下午10:57
 **/
@Configuration
public class AppConfig {
    @Bean
    public JwtCheckGatewayFilterFactory jwtCheckGatewayFilterFactory(){
        return new JwtCheckGatewayFilterFactory();
    }
}

 

三、网关服务的配置文件中配置 自定义过滤器 生效的服务

 

 这里只配置了 php 这个服务,java 这个服务不使用这个过滤器规则

posted @ 2018-09-09 23:40 liugx 阅读(...) 评论(...) 编辑 收藏