共计 1938 个字符,预计需要花费 5 分钟才能阅读完成。
背景
须要对 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<Void> 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);
}
}
正文完