【发布时间】:2021-12-26 13:20:16
【问题描述】:
在下面的代码 sn-p 中,我试图将我的请求与自定义谓词进行匹配。在谓词被评估为假后,我想发回一个自定义状态代码(下面的 sn-p 中的 403 禁止),而不是在谓词失败时发送的默认 404。这是我尝试过的。
路线定位器
@Bean
public RouteLocator customRoutesLocator(RouteLocatorBuilder builder
AuthenticationRoutePredicateFactory arpf) {
return builder.routes()
.route("id1", r ->r.path("/app1/**")
.uri("lb://id1")
.predicate(arpf.apply(new Config()))).build();
}
AuthenticationRoutePredicateFactory
public class AuthenticationRoutePredicateFactory
extends AbstractRoutePredicateFactory<AuthenticationRoutePredicateFactory.Config> {
public AuthenticationRoutePredicateFactory() {
super(Config.class);
}
@Override
public Predicate<ServerWebExchange> apply(Config config) {
return (ServerWebExchange t) -> {
try {
Boolean isRequestAuthenticated = checkAuthenticated();
return isRequestAuthenticated;
}
} catch (HttpClientErrorException e) {
//This status code does not carried forward and 404 is displayed instead.
t.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
return false;
}
};
}
@Validated
public static class Config {
public Config() {
}
}
private Boolean checkAuthenticated() {
// Some sample logic that makes a REST call and returns TRUE/FALSE/HttpClientErrorException
//Not shown here for simplicity.
return true;
}
}
当谓词返回为真时,请求被转发到 URI。但是,在显示错误评估 404 时,我需要显示 403(在 HttpClientErrorException 上)。这是期望带有自定义状态代码的响应的正确方法吗?此外,我还阅读了为给定路由实现自定义 webfilters 的内容,该路由可能会在转发请求之前修改响应对象。在这种情况下,有没有办法在谓词失败时调用过滤器?
【问题讨论】:
标签: java spring-boot spring-cloud-gateway