拦截器filter
使用拦截器对请求进行拦截,查看请求头是否携带token
可以看到,拦截器引入了web的依赖
前端的请求会经过网关(gateway),网关用的是netty服务器,会和web默认的tomcat服务器冲突,但是前端过来的请求也需要校验请求头是否携带了token,要怎么实现呢?
这就需要用到过滤器(filter)了
对于单token校验:只需要在gateway校验token即可,校验通过后,各个微服务之间的相互调用就不需要校验token了
package com.gmgx.filters;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;
@Component
@Slf4j
public class TokenFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//gateway引不了web的依赖,因此不能用HttpServletRequest,用ServerWebExchange替代
ServerHttpRequest request = exchange.getRequest();
HttpHeaders headers = request.getHeaders();
List<String> authorization = headers.get("Authorization");
String token = authorization.get(0);
if (token == null) {
throw new RuntimeException("token丢失");
}
//到下一个过滤器(由过滤器链)
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
System.out.println("then(Mono.fromRunnable(() -> {}))是一个附加的操作," +
"它在chain.filter(exchange)的Mono<Void>完成之后执行。");
System.out.println("通常用于在过滤器链完成后执行一些清理工作、日志记录或其他不需要等待结果的异步任务。");
}));
}
@Override
public int getOrder() {
//数字越小,过滤器的优先级越高
return 0;
}
}