package com.liron.filter;
import com.liron.system.SystemConstants;
import com.liron.utils.AppJwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 要先获取到用户发送过来的请求头才行
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
//+ 2.判断当前的请求 是否 是登录的请求 如果是 ,则放行
String path = request.getURI().getPath();
if(path.equals("/x/login")){
return chain.filter(exchange);
}
MultiValueMap<String, String> params = request.getHeaders();
// 然后拿到请求头里面的token
String token = params.getFirst("token");
if(StringUtils.isEmpty(token)){
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return response.setComplete();//完成响应 返回 后面就不执行了
}
// 校验token
Integer verifyToken = AppJwtUtil.verifyToken(token);
if (!verifyToken.equals(SystemConstants.JWT_OK)){
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return response.setComplete();
}
// 放行
return chain.filter(exchange);
}
@Override
public int getOrder() {
// put the filter first
return 0;
}
}
nacos网关自定义过滤器
于 2023-03-09 11:34:13 首次发布
该篇文章介绍了一个名为AuthorizeFilter的组件,它是SpringCloudGateway的全局过滤器。这个过滤器用于检查请求头中的token,对非登录请求进行权限验证。如果请求路径不是登录接口且token无效,将返回Unauthorized状态码。
摘要由CSDN通过智能技术生成