如何使用Spring WebFlux WebFilter结束请求并发送正确的响应?

时间:2018-01-26 11:33:23

标签: java spring jwt spring-webflux

我在标头中使用JWT来验证用户请求。

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    String token = exchange.getRequest().getHeaders().getFirst("token");
    // Verify a Token
    try {
        Algorithm algorithm = Algorithm.HMAC256("secret");
        JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer("auth0")
                .build(); //Reusable verifier instance
        DecodedJWT jwt = verifier.verify(token);
    } catch (UnsupportedEncodingException exception) {
        // send internal server error in response
    } catch (JWTVerificationException exception) {
        // send invalid token
    }
    return chain.filter(exchange);
}

当我使用

return Mono.empty();

它结束了请求,但是如何设置正确的响应?例如&#34;无效令牌&#34;或&#34;内部服务器错误&#34;作为回应。

3 个答案:

答案 0 :(得分:1)

也许这会有所帮助,这适用于x509身份验证,但它适用于JWT。

检查Authentication by certificate for WebFlux?

要点是:

  1. 使用身份验证转换器提取凭据(身份验证筛选器将负责调用ReactiveAuthenticationManager以对提取的凭据进行身份验证)
  2. 如果需要,使用AuthenticationEntryEndpoint在身份验证失败时自定义回复客户端
  3. 希望这有帮助

答案 1 :(得分:0)

在catch块中,您可以执行以下操作或重新抛出异常,以便通过实现&#34; org.springframework.web.server.WebExceptionHandler&#34;来获得一些GlobalExceptionHandler。在那里你也可以有这个逻辑。这里的Key是使用DataBufferFactory,然后使用Jackson的ObjectMapper将您的自定义错误对象序列化为字符串,然后编写响应以及使用exchange.getResponse()设置HTTP状态.setStatusCode

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Autowired
    ObjectMapper objMapper;

        ApiError apiError = new ApiError(HttpStatus.UNAUTHORIZED);
        apiError.setTimestamp(LocalDateTime.now());
        apiError.setMessage("Invalid token" + exception.getMessage() + ":"+exception.getLocalizedMessage());
        DataBuffer buf = null;
        try {
            buf = dataBufferFactory.wrap(objMapper.writeValueAsBytes(apiError));
        } catch (JsonProcessingException e) {
            LOG.debug("Exception during processing JSON", e);
            apiError.setMessage(e.getMessage());
        }
        if(buf == null) buf = dataBufferFactory.wrap("".getBytes());
        exchange.getResponse().setStatusCode(apiError.getStatus());
        return exchange.getResponse().writeWith(Flux.just(buf));

ApiError是一个自定义类,它具有HTTP状态和时间戳以及类似下面的内容或您的自定义数据结构。

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;

import org.springframework.http.HttpStatus;

import com.fasterxml.jackson.annotation.JsonFormat;

import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ApiError  implements Serializable{

       private HttpStatus status;
       @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MM/dd/yyyy hh:mm:ss a")
       private LocalDateTime timestamp;
       private String message;
       private String debugMessage;


       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();
       }





}

答案 2 :(得分:0)

您可以修改Response的标题:

not_found_images = not_found_images.append(row, ignore_index=True)

我找不到写Response正文的方法