如何使AuditorAware与Spring Data Mongo Reactive配合使用

问题描述 投票:1回答:1

Spring Security 5提供了ReactiveSecurityContextHolder to fetch the SecurityContext from a Reactive context,但是当我想实现AuditorAware并自动获得试镜工作时,它却无法正常工作。目前我找不到ReactiveAuditorAware变种。

@Bean
public AuditorAware<Username> auditor() {
    return () -> ReactiveSecurityContextHolder.getContext()
        .map(SecurityContext::getAuthentication)
        .log()
        .filter(a -> a != null && a.isAuthenticated())
        .map(Authentication::getPrincipal)
        .cast(UserDetails.class)
        .map(auth -> new Username(auth.getName()))
        .switchIfEmpty(Mono.empty())
        .blockOptional();
}

我在我的启动@EnableMongoAuduting课程中添加了Application

关于Mongo文档类。我添加了试听相关的注释。

@CreatedDate
private LocalDateTime createdDate;

@CreatedBy
private Username author;

当我添加帖子时,createdDate被填充,但是author为null。

{"id":"5a49ccdb9222971f40a4ada1","title":"my first post","content":"content of my first post","createdDate":"2018-01-01T13:53:31.234","author":null}

完整的代码是here,基于Spring Boot 2.0.0.M7。

spring spring-security spring-data-mongodb project-reactor spring-webflux
1个回答
-2
投票

要填充createdBy属性,需要将auditorAware bean与注释@EnableMongoAuditing链接

在MongoConfig类中,定义您的bean:

@Bean(name = "auditorAware")
public AuditorAware<String> auditor() {
    ....
}

并在注释中使用它:

@Configuration
@EnableMongoAuditing(auditorAwareRef="auditorAware")
class MongoConfig {
    ....
}
© www.soinside.com 2019 - 2024. All rights reserved.