SpringCloud初体验:七、gateway⽹关服务如何做token验证
说说背景:假如有⼀个⽤户服在⽤户登录后,⽣成⼀个token给到客户端,⽤户每次请求时都需要这个token,于是每次都会在⽹关 gateway 校验,校验通过后⽹关从token中解析出userId,然后将userId送到各个服务。
⼀、需要⾃定义 GatewayFilterFactory 继承 AbstractGatewayFilterFactory 抽象类,代码如下:
package _api_gateway_server.filter;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.active.ServerHttpResponse;
publisher.Mono;
/**
* JWT验证的过滤器
*springcloud怎么读音
* @author szliugx@gmail
* @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 = Request().getHeaders().getFirst("Authorization");
//校验jwtToken的合法性
if (jwtToken != null) {
// 合法
// 将⽤户id作为参数传递下去
return chain.filter(exchange);
}
//不合法(响应未登录的异常)
ServerHttpResponse response = Response();
/
/设置headers
HttpHeaders httpHeaders = Headers();
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().Bytes());
return response.writeWith(Mono.just(bodyDataBuffer));
};
}
public static class Config {
/
/Put the configuration properties for your filter here
}
}
View Code
⼆、需要将⾃定义的 GatewayFilterFactory 注⼊到Spring 中
package _api_fig;
import _api_gateway_server.filter.JwtCheckGatewayFilterFactory;
import t.annotation.Bean;
import t.annotation.Configuration;
/**
* 应⽤配置
*
* @author szliugx@gmail
* @create 2018-09-09 下午10:57
**/
@Configuration
public class AppConfig {
@Bean
public JwtCheckGatewayFilterFactory jwtCheckGatewayFilterFactory(){
return new JwtCheckGatewayFilterFactory();
}
}
三、⽹关服务的配置⽂件中配置⾃定义过滤器⽣效的服务
这⾥只配置了 php 这个服务,java 这个服务不使⽤这个过滤器规则
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论