【发布时间】:2021-10-23 19:26:13
【问题描述】:
在spring cloud gateway中,添加了一个过滤器,用于检查身份验证和授权以进一步处理请求。我正在使用 feign 客户端调用身份验证服务,但是通过 spring 云网关调用我的服务时出现以下错误。
java.lang.IllegalStateException: block()/blockFirst()/blockLast() 是阻塞的,线程 reactor-http-epoll-3\n\tat reactor.core.publisher.BlockingSingleSubscriber.blockingGet( BlockingSingleSubscriber.java:83)\n\tSuppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: \n在以下站点观察到错误:\n\t|_ checkpoint ⇢ org.springframework.cloud.gateway。 filter.WeightCalculatorWebFilter ....."
我想知道我使用的架构是否错误。如何进行?我被这个错误困住了。
@Autowired
private AuthenticationService authService;
// route validator
@Autowired
private RouterValidator routerValidator;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
if (routerValidator.isSecured.test(request)) {
log.info("Accessing the restricted path");
if (this.isAuthMissing(request))
return this.onError(exchange, "Authorization header is missing in request", HttpStatus.UNAUTHORIZED);
final String token = this.getAuthHeader(request);
log.info("before authservice call");
AuthenticationResponse user = authService.isTokenValid(token);
log.info("after authservice call");
if (!user.isValid())
return this.onError(exchange, "Authorization header is invalid", HttpStatus.UNAUTHORIZED);
log.info("before calling populatedRequest");
this.populateRequestWithHeaders(exchange, user);
}
return chain.filter(exchange);
}
private Mono<Void> onError(ServerWebExchange exchange, String err, HttpStatus httpStatus) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(httpStatus);
return response.setComplete();
}
private String getAuthHeader(ServerHttpRequest request) {
return request.getHeaders().getOrEmpty("Authorization").get(0);
}
private boolean isAuthMissing(ServerHttpRequest request) {
log.info("inside auth missing");
return !request.getHeaders().containsKey("Authorization");
}
private void populateRequestWithHeaders(ServerWebExchange exchange, AuthenticationResponse authRes) {
log.info("About to mutate the request->{}",exchange);
exchange.getRequest().mutate()
.header("id",Integer.toString(authRes.getUserId()))
.build();
}
假装界面
@Autowired
private AuthenticationFeign auth;
public AuthenticationResponse isTokenValid(String token) {
return auth.getValidity(token);
}
【问题讨论】:
-
feign 被阻塞,不推荐在网关中使用
-
@spencergibb 谢谢我现在对 webclient 做同样的事情。
标签: spring-boot spring-security spring-cloud spring-cloud-feign openfeign