如果授权标头不存在,则无法在Webfilter中发送自定义正文

时间:2018-01-26 01:20:30

标签: spring spring-boot spring-webflux spring-web

我试图使用Webfilter拦截Spring Boot Webflux应用程序(Spring boot 2.0.0.M7)中的所有请求,并检查是否存在"授权"头。如果不存在,我想停止请求处理并发送自定义HttpStatus和自定义正文。自定义HttpStatus正在工作,但我无法将自定义消息写入HTTP正文。

下面
import java.time.LocalDateTime;

import org.apache.commons.lang.SerializationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;

public class RequestContextFilter implements WebFilter{

    Logger LOG = LoggerFactory.getLogger(RequestContextFilter.class);

    @Autowired
    private WebClient.Builder webclientBuilder;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        LOG.debug("Inside RequestContextFilter.."+ exchange);
        String authorizationHeader = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if(authorizationHeader == null) {
            exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
            ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST);
            apiError.setMessage("Missing Authorization Header");
            apiError.setTimestamp(LocalDateTime.now());
   // The below code of writing to body is NOT WORKING
            exchange.getResponse().writeWith(Mono.just(new DefaultDataBufferFactory().wrap(SerializationUtils.serialize(apiError))));
            return Mono.empty();
        }
        return chain.filter(exchange);

    }


}

ApiError.java类只是我想要包含在响应中的自定义对象。

public class ApiError  implements Serializable{

       private HttpStatus status;
       @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
       private LocalDateTime timestamp;
       private String message;
       private String debugMessage;
       private List<ApiSubError> subErrors;


       public ApiError() {
           timestamp = LocalDateTime.now();
       }

       public ApiError(HttpStatus status) {
           this();
           this.status = status;
       }

       public ApiError(HttpStatus status, Throwable ex) {
           this();
           this.status = status;
           this.message = "Unexpected error";
           this.debugMessage = ex.getLocalizedMessage();
       }

       public ApiError(HttpStatus status, String message, Throwable ex) {
           this();
           this.status = status;
           this.message = message;
           this.debugMessage = ex.getLocalizedMessage();
       }





}

我卷曲端点,这个Webfilter确实有效,它发送了正确的HttpStatus代码400,但没有ApiError。

请求(无授权标头):

curl -X GET "http://localhost:8080/accounts"--verbose

响应:

HTTP/1.1 400 Bad Request
content-length: 0

状态有效并且正在调用过滤器但没有对象响应。我确实尝试使用jackson将原始字节转换为JSON后写入字节到DataBufferFactory,但它不起作用。

2 个答案:

答案 0 :(得分:2)

+1 @bsamartins说的话。

现在关于您的特定解决方案:writeWith方法返回Publisher。如果没有订阅它,那么什么都没发生。你应该替换

exchange.getResponse().writeWith(Mono.just(new DefaultDataBufferFactory().wrap(SerializationUtils.serialize(apiError))));
return Mono.empty();

return exchange.getResponse()
               .writeWith(Mono.just(new DefaultDataBufferFactory().wrap(SerializationUtils.serialize(apiError))));

通过该更改,Spring WebFlux将订阅返回的Publisher,您的代码将写入响应。

答案 1 :(得分:1)

您可以使用Spring AuthenticationWebFilter而不是创建新的。 看看这个question如何使用它。

设置您自己的authenticationConverter以从标头中提取凭据,然后您可以实施自己的AuthenticationEntryPoint并在过滤器上设置它以向客户端发送自定义响应。

您可以查看http基本身份验证的默认实现,了解如何实现该目标。

相关问题