gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:38:31 26 4
gpt4 key购买 nike

我在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com