Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add some data in body of response for Cloud Api Gateway

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. 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));

What I'm doing wrong?

like image 486
Alex Avatar asked Jan 28 '18 20:01

Alex


1 Answers

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));
  }
}
like image 59
Alex Avatar answered Sep 25 '22 01:09

Alex