我在Spring webflux上构建应用程序,并且因为Spring安全性webflux(v.M5)在异常处理方面的行为不像Spring 4而被卡住了。
我看到以下关于如何自定义spring security webflux的帖子: Spring webflux custom authentication for API
如果我们在ServerSecurityContextRepository.load中抛出异常,那么Spring会将http标头更新为500,而我无法操纵这个异常。
但是,控制器中抛出的任何错误都可以使用常规的@ControllerAdvice来处理,它只是弹出webflux安全性。
无论如何都要处理spring webflux安全性中的异常吗?
答案 0 :(得分:3)
我刚刚通过大量文档,遇到了类似的问题。
我的解决方案是使用ResponseStatusException。似乎可以理解Spring-security的AccessException。
.doOnError(
t -> AccessDeniedException.class.isAssignableFrom(t.getClass()),
t -> AUDIT.error("Error {} {}, tried to access {}", t.getMessage(), principal, exchange.getRequest().getURI())) // if an error happens in the stream, show its message
.onErrorMap(
SomeOtherException.class,
t -> { return new ResponseStatusException(HttpStatus.NOT_FOUND, "Collection not found");})
;
如果这对你来说是正确的方向,我可以提供更好的样本。
答案 1 :(得分:3)
我找到的解决方案是创建一个实现ErrorWebExceptionHandler
的组件。在Spring Security过滤器之前运行ErrorWebExceptionHandler
bean的实例。这是我使用的一个示例:
@Slf4j
@Component
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {
@Autowired
private DataBufferWriter bufferWriter;
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
AppError appError = ErrorCode.GENERIC.toAppError();
if (ex instanceof AppException) {
AppException ae = (AppException) ex;
status = ae.getStatusCode();
appError = new AppError(ae.getCode(), ae.getText());
log.debug(appError.toString());
} else {
log.error(ex.getMessage(), ex);
}
if (exchange.getResponse().isCommitted()) {
return Mono.error(ex);
}
exchange.getResponse().setStatusCode(status);
return bufferWriter.write(exchange.getResponse(), appError);
}
}
如果您正在注入HttpHandler
,那么它有点不同但想法是一样的。
更新:为了完整性,这是我的DataBufferWriter
对象,即@Component
:
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class DataBufferWriter {
private final ObjectMapper objectMapper;
public <T> Mono<Void> write(ServerHttpResponse httpResponse, T object) {
return httpResponse
.writeWith(Mono.fromSupplier(() -> {
DataBufferFactory bufferFactory = httpResponse.bufferFactory();
try {
return bufferFactory.wrap(objectMapper.writeValueAsBytes(object));
} catch (Exception ex) {
log.warn("Error writing response", ex);
return bufferFactory.wrap(new byte[0]);
}
}));
}
}
答案 2 :(得分:1)
不需要注册任何bean并更改默认的Spring行为。尝试使用更优雅的解决方案:
我们有
:.load方法返回Mono
public class HttpRequestHeaderSecurityContextRepository implements ServerSecurityContextRepository {
....
@Override
public Mono<SecurityContext> load(ServerWebExchange exchange) {
List<String> tokens = exchange.getRequest().getHeaders().get("X-Auth-Token");
String token = (tokens != null && !tokens.isEmpty()) ? tokens.get(0) : null;
Mono<Authentication> authMono = reactiveAuthenticationManager
.authenticate( new HttpRequestHeaderToken(token) );
return authMono
.map( auth -> (SecurityContext)new SecurityContextImpl(auth))
}
}
问题是::如果authMono
将包含error
而不是Authentication
-spring将返回带有 500的http响应状态(表示“未知内部错误”),而不是 401 。甚至错误是AuthenticationException或其子类-都没有意义-Spring将返回500。
但是对于我们来说很明显:AuthenticationException应该会产生401错误...
要解决该问题,我们必须帮助Spring如何将Exception转换为HTTP响应状态代码。
要做到这一点,我们可以只使用适当的Exception类:ResponseStatusException
或仅将原始异常映射到该异常(例如,通过将onErrorMap()
添加到authMono
对象)。查看最终代码:
public class HttpRequestHeaderSecurityContextRepository implements ServerSecurityContextRepository {
....
@Override
public Mono<SecurityContext> load(ServerWebExchange exchange) {
List<String> tokens = exchange.getRequest().getHeaders().get("X-Auth-Token");
String token = (tokens != null && !tokens.isEmpty()) ? tokens.get(0) : null;
Mono<Authentication> authMono = reactiveAuthenticationManager
.authenticate( new HttpRequestHeaderToken(token) );
return authMono
.map( auth -> (SecurityContext)new SecurityContextImpl(auth))
.onErrorMap(
er -> er instanceof AuthenticationException,
autEx -> new ResponseStatusException(HttpStatus.UNAUTHORIZED, autEx.getMessage(), autEx)
)
;
)
}
}