本文介绍了Spring WebFlux、安全和请求正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用请求体的HMAC保护用Spring Boot、WebFlux和Spring安全实现的rest API。简单地说,在高级别上-请求附带具有请求正文的散列值的头部,因此我必须读取头部、读取正文、计算正文的散列值并与头部值进行比较。

我认为我应该实现ServerAuthenticationConverter,但到目前为止我找到的所有示例都只能查看请求头,而不是正文,我不确定我是否只能读取正文,或者我是否应该使用缓存的正文来包装/突变请求,以便它可以被底层组件第二次使用?

是否可以使用以下内容:

public class HttpHmacAuthenticationConverter implements ServerAuthenticationConverter {

    @Override
    public Mono<Authentication> convert(ServerWebExchange exchange) {
        exchange.getRequest().getBody()
                .next()
                .flatMap(dataBuffer -> {
                    try {
                        return Mono.just(StreamUtils.copyToString(dataBuffer.asInputStream(), StandardCharsets.UTF_8));
                    } catch (IOException e) {
                        return Mono.error(e); 
                    }
                })
                ...


我在copyToString行收到来自IDE的警告:不适当地阻止方法调用

有什么指导原则或例子吗?

谢谢!

我也尝试过:

    @Override
    public Mono<Authentication> convert(ServerWebExchange exchange) {
        return Mono.justOrEmpty(exchange.getRequest().getHeaders().toSingleValueMap())
                .zipWith(exchange.getRequest().getBody().next()
                        .flatMap(dataBuffer -> Mono.just(dataBuffer.asByteBuffer().array()))
                )
                .flatMap(tuple -> create(tuple.getT1(), tuple.getT2()));

但这不起作用--永远不会执行最后一行的create()方法中的代码。

推荐答案

我让它工作。正在发布我的代码以供参考。

需要两个组件才能使其工作-WebFilter读取和缓存请求正文,以便可以多次使用它,以及ServerAuthenticationConverter,它将计算正文上的哈希并验证签名。

public class HttpRequestBodyCachingFilter implements WebFilter {
private static final byte[] EMPTY_BODY = new byte[0];

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    // GET and DELETE don't have a body
    HttpMethod method = exchange.getRequest().getMethod();
    if (method == null || method.matches(HttpMethod.GET.name()) || method.matches(HttpMethod.DELETE.name())) {
        return chain.filter(exchange);
    }

    return DataBufferUtils.join(exchange.getRequest().getBody())
            .map(dataBuffer -> {
                byte[] bytes = new byte[dataBuffer.readableByteCount()];
                dataBuffer.read(bytes);
                DataBufferUtils.release(dataBuffer);
                return bytes;
            })
            .defaultIfEmpty(EMPTY_BODY)
            .flatMap(bytes -> {
                ServerHttpRequestDecorator decorator = new ServerHttpRequestDecorator(exchange.getRequest()) {
                    @Nonnull
                    @Override
                    public Flux<DataBuffer> getBody() {
                        if (bytes.length > 0) {
                            DataBufferFactory dataBufferFactory = exchange.getResponse().bufferFactory();
                            return Flux.just(dataBufferFactory.wrap(bytes));
                        }
                        return Flux.empty();
                    }
                };
                return chain.filter(exchange.mutate().request(decorator).build());
            });
}

}

public class HttpJwsAuthenticationConverter implements ServerAuthenticationConverter {
private static final byte[] EMPTY_BODY = new byte[0];

@Override
public Mono<Authentication> convert(ServerWebExchange exchange) {
    return DataBufferUtils.join(exchange.getRequest().getBody())
            .map(dataBuffer -> {
                byte[] bytes = new byte[dataBuffer.readableByteCount()];
                dataBuffer.read(bytes);
                DataBufferUtils.release(dataBuffer);
                return bytes;
            })
            .defaultIfEmpty(EMPTY_BODY)
            .flatMap(body -> create(
                    exchange.getRequest().getMethod(),
                    getFullRequestPath(exchange.getRequest()),
                    exchange.getRequest().getHeaders(),
                    body)
            );
}

...

Converter中的create方法实现基于请求方法、路径、Header和Body验证签名的逻辑。如果成功,则返回Authentication的实例;如果失败,则返回Mono.empty()的实例。

布线如下:

public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http.authorizeExchange().pathMatchers(PATH_API).authenticated()
      ...
      .and()
      .addFilterBefore(new HttpRequestBodyCachingFilter(), SecurityWebFiltersOrder.AUTHENTICATION)
      .addFilterAt(jwtAuthenticationFilter(...), SecurityWebFiltersOrder.AUTHENTICATION);
}

private AuthenticationWebFilter jwtAuthenticationFilter(ReactiveAuthenticationManager authManager) {
    AuthenticationWebFilter authFilter = new AuthenticationWebFilter(authManager);
    authFilter.setServerAuthenticationConverter(new HttpJwsAuthenticationConverter());
    authFilter.setRequiresAuthenticationMatcher(ServerWebExchangeMatchers.pathMatchers(PATH_API));
    return authFilter;
}

@Bean
public ReactiveAuthenticationManager reactiveAuthenticationManager() {
    return Mono::just;
}

   
}

这篇关于Spring WebFlux、安全和请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 17:38