SpringCloud整合GateWay+Sa-Token做登录验证(干货)
    		       		warning:
    		            这篇文章距离上次修改已过421天,其中的内容可能已经有所变动。
    		        
        		                
                
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
 
import java.nio.charset.StandardCharsets;
 
/**
 * 网关中的登录验证过滤器
 */
public class LoginFilter implements GlobalFilter {
 
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 检查请求是否需要登录
        // 这里的逻辑可以根据实际情况进行定制,例如检查请求的URL路径或者Header等
        // 如果需要登录验证,则直接返回未认证的响应
        if (需要登录验证) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String result = "{\"code\":401,\"msg\":\"未登录或登录失效,请重新登录!\"}";
            byte[] bytes = result.getBytes(StandardCharsets.UTF_8);
            DataBufferUtils.write(response.bufferFactory().wrap(bytes), response);
            return response.setComplete();
        }
 
        // 如果不需要登录验证,则继续执行后续的过滤器和路由
        return chain.filter(exchange);
    }
}这个代码示例展示了如何在Spring Cloud Gateway中实现一个简单的登录验证过滤器。当请求需要登录验证时,过滤器会返回一个未认证的HTTP响应。这个过滤器可以被用作一个基本的登录保护,也可以根据实际需求进行功能扩展。
评论已关闭