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

标签 java spring jwt spring-webflux

我在 header 中使用 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();

它结束了请求,但是如何设置一个合适的响应呢?例如响应中出现“无效 token ”或“内部服务器错误”。

最佳答案

在 catch block 中,您可以执行以下操作或重新抛出异常,这样您就可以通过实现“org.springframework.web.server.WebExceptionHandler”来获得一些 GlobalExceptionHandler,并且您也可以拥有此逻辑。这里的关键是使用 DataBufferFactory,然后使用 Jackson 的 ObjectMapper 将您的自定义错误对象序列化为字符串,然后写入响应并使用 exchange.getResponse().setStatusCode 设置 HTTP 状态

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





}

关于java - 如何使用 Spring WebFlux WebFilter 结束请求并发送正确的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48460562/

相关文章:

rest - go-restful + JWT认证

java - Java 对象数组可以将元素初始化为非空值吗?

java - 数据绑定(bind) Spring

java - 如何在列注释中设置默认值

javascript - 使用客户端指纹对 JWT token 进行编码?

validation - 如何在 oAuth 2.0/owin 中自定义 JWT token 验证?

java - 使用 Java 测试文件损坏和损坏

java - "uses unchecked or unsafe operations"

java - 如果枚举类是Java方法中的参数,如何获取枚举值?

尝试使用 elvis 运算符编译表达式时,Spring SPEL 评估抛出 ArrayIndexOutOfBoundsException