SpringGateway中对SpringActuator路径进行权限验证

背景
【SpringGateway中对SpringActuator路径进行权限验证】需要对spingActuator的监测路径进行拦截,从而实现弹窗输入登录信息的功能,但是gateway提供的GlobalFilter拦截器不生效,故研究了一番
解决方式
使用WebFilter进行拦截,拦截器代码如下:

import org.springframework.core.annotation.Order; import org.springframework.http.HttpHeaders; 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.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; import reactor.core.publisher.Mono; import sun.misc.BASE64Decoder; import java.io.IOException; import java.util.Objects; @Order(2) @Component public class ActuatorFilter implements WebFilter { @Override public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); ServerHttpResponse response = exchange.getResponse(); String uriPath = request.getURI().getPath(); if(uriPath.startsWith("/actuator/")) { String auth = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION); if(Objects.isNull(auth)){ System.out.println("校验请求头为空,需进行登录.."); response.getHeaders().add(HttpHeaders.WWW_AUTHENTICATE,"Basic realm=".""); response.setStatusCode(HttpStatus.UNAUTHORIZED); return response.setComplete(); }else { System.out.println("auth:" + auth); BASE64Decoder decoder = new BASE64Decoder(); String[] values = new String[0]; try { values = new String(decoder.decodeBuffer(auth.split(" ")[1])).split(":"); } catch (IOException e) { throw new RuntimeException(e); } if (values.length == 2) { String username = values[0]; String pwd = values[1]; System.out.println("username:" + username); System.out.println("pwd:" + pwd); if(Objects.equals("test",username) && Objects.equals("test",pwd)){ return chain.filter(exchange); }else { response.getHeaders().add(HttpHeaders.WWW_AUTHENTICATE,"Basic realm=".""); response.setStatusCode(HttpStatus.UNAUTHORIZED); return response.setComplete(); } } } } return chain.filter(exchange); } }

    推荐阅读