如何在Cloud Api Gateway的响应正文中添加一些数据 [英] How to add some data in body of response for Cloud Api Gateway

查看:436
本文介绍了如何在Cloud Api Gateway的响应正文中添加一些数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向云API网关添加一些身份验证逻辑.我添加了GatewayFilter:

I'm adding some auth logic into cloud api gateway. I've added GatewayFilter:

import java.util.List;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PatternMatchUtils;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

public class AuthorizationFilter implements GatewayFilter {
  @Override
  public Mono<Void> filter(
    ServerWebExchange exchange, GatewayFilterChain chain) {
    List<String> authorization = exchange.getRequest().getHeaders().get("Authorization");
    if (CollectionUtils.isEmpty(authorization) &&
      !PatternMatchUtils.simpleMatch(URL_WITHOUT_AUTH, exchange.getRequest().getURI().toString())) {
      exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
      //Add some custom data in body of the response
      return exchange.getResponse().setComplete();
    }
    String token = authorization.get(0).split(" ")[1];
    // token validation
    return chain.filter(exchange);
  }
}

但是我无法在响应正文中添加一些数据.您能帮我了解它的工作原理以及如何对其进行自定义吗?

but I can't add some data into the body of response. Can you please help me to find out how it works and how I can customize that?

P.S. 我正在尝试使用通量添加一些数据作为响应,但是它不起作用:

P.S. I'm trying to add some data in response using flux but it doesn't work:

 DataBuffer b = exchange.getResponse().bufferFactory().allocateBuffer(256);
      b.write("12345".getBytes());
      return exchange.getResponse().writeWith(s -> Flux.just(b));

我做错了什么?

推荐答案

在春季工作人员的帮助下,我得以使它工作.因此,除了直接写响应之外,我还必须抛出自定义异常并正确处理它:

After some help from spring guys, I was able to make it work. So instead of writing directly to response I had to throw my custom exception and handle it properly:

@Bean
public ErrorWebExceptionHandler myExceptionHandler() {
  return new MyWebExceptionHandler();
}

public class MyWebExceptionHandler implements ErrorWebExceptionHandler {
  @Override
  public Mono<Void> handle(
    ServerWebExchange exchange, Throwable ex) {
    byte[] bytes = "Some text".getBytes(StandardCharsets.UTF_8);
    DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
    return exchange.getResponse().writeWith(Flux.just(buffer));
  }
}

这篇关于如何在Cloud Api Gateway的响应正文中添加一些数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆