网关登录拦截
接下来,我们在gateway编写过滤器,对用户的token进行校验,如果发现未登录,则进行拦截。
引入jwt相关配置
既然是登录拦截,一定是前置拦截器,我们在gateway
中定义。
首先在pom.xml中,引入所需要的依赖:
然后编写application.yml属性文件,添加如下内容:
jwt:
pubKeyPath: C:\\tmp\\rsa\\rsa.pub # 公钥地址
cookieName: TOKEN # cookie的名称
编写属性类,读取公钥:
@Data
@Slf4j
@ConfigurationProperties(prefix = "jwt")
public class JwtProperties {
private String pubKeyPath;// 公钥
private PublicKey publicKey; // 公钥
private String cookieName;
@PostConstruct
public void init(){
try {
// 获取公钥和私钥
this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
} catch (Exception e) {
log.error("初始化公钥失败!", e);
throw new RuntimeException();
}
}
}
自定义token过滤器
gateway自定义过滤器分3步:
-
自定义定义认证过滤器
-
自定义认证过滤器工厂
-
配置中使用自定义过滤器
过滤器AuthGatewayFilter
过滤器的基本逻辑:
-
获取cookie中的token
-
通过JWT对token进行校验
-
通过:则放行;不通过:则响应认证未通过
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class AuthGatewayFilter implements GatewayFilter {
@Autowired
private JwtProperties jwtProperties;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 获取request和response,注意:不是HttpServletRequest及HttpServletResponse
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
// 获取所有cookie
MultiValueMap<String, HttpCookie> cookies = request.getCookies();
// 如果cookies为空或者不包含指定的token,则相应认证未通过
if (CollectionUtils.isEmpty(cookies) || !cookies.containsKey(this.jwtProperties.getCookieName())) {
// 响应未认证!
response.setStatusCode(HttpStatus.UNAUTHORIZED);
// 结束请求
return response.setComplete();
}
// 获取cookie
HttpCookie cookie = cookies.getFirst(this.jwtProperties.getCookieName());
try {
// 校验cookie
JwtUtils.getInfoFromToken(cookie.getValue(), this.jwtProperties.getPublicKey());
} catch (Exception e) {
e.printStackTrace();
// 校验失败,响应未认证
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return response.setComplete();
}
// 认证通过放行
return chain.filter(exchange);
}
}
过滤器工厂AuthGatewayFilterFactory
@Component
public class AuthGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
@Autowired
private AuthGatewayFilter authGatewayFilter;
@Override
public GatewayFilter apply(Object config) {
return authGatewayFilter;
}
}