Spring-Gateway 全局拦截器(GlobalFilter)使用

package com.lamb.config;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author lamb
 * 2023/12/27 15:50
 * 自定义身份过滤器  身份不为admin则进行拦截
 * @version 1.0.0
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        //获取登录的用户名
        String authorization = queryParams.getFirst("authorization");
        if ("admin".equals(authorization)) {
            //放行
            return chain.filter(exchange);
        }
        //未授权 拦截
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);

        return exchange.getResponse().setComplete();
    }
/**
*@description: 这边实现ordered接口 将自定义的全局拦截器优先执行,也可以使用@Order注解达到一样的效果
*/
    @Override
    public int getOrder() {
        return -1;
    }
}

你可能感兴趣的:(spring,gateway,java)