【问题标题】:Spring webflux security with mock user for the backendSpring webflux 安全性与后端的模拟用户
【发布时间】:2021-05-11 16:45:09
【问题描述】:

我的spring webflux安全码是,

@Bean
    public SecurityWebFilterChain securitygWebFilterChain(final ServerHttpSecurity http) {

        http.securityContextRepository(securityContextRepository);
        return http.authorizeExchange().matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
                .pathMatchers(props.getSecurity().getIgnorePatterns()).permitAll().anyExchange().authenticated()
                .and().formLogin()
                .and().exceptionHandling()
                .authenticationEntryPoint((exchange, exception) -> Mono.error(exception))
                .accessDeniedHandler((exchange, exception) -> Mono.error(exception))
                .and().build();
    }

现在,我有下面的代码来获取登录用户的详细信息。

public Mono<AppUserDetails> getUser() {
    Mono<Principal> principalMono = ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication).cast(Principal.class);
    
            principalMono.flatMap(principal -> {
                if (principal instanceof AuthenticatedUserToken) {
                    final AppUserDetails user = ((AuthenticatedUserToken<?>) principal).getUser();
                    return Mono.just(user);
                } 
    
                return Mono.error(() -> new IllegalArgumentException("Invalid access"));
            }).switchIfEmpty(Mono.defer(() -> {
                return Mono.empty();
            }));
}

我有一个 API 来创建一个项目,并且项目表有审计列以及 createdBy 用户。我正在使用上面的代码(getUser() 方法)来检索登录的用户并从那里获取 userId。

现在,尝试通过 postman 测试此 API,仅使用 userId 为 1 的模拟用户,而不是使用真实用户登录,因为前端尚未准备好。

如何使用模拟用户运行 Spring Boot 应用程序并在调用 getUser() 方法时返回模拟用户 ID,以便进行端到端测试。

【问题讨论】:

  • 你试过什么?发布您尝试过的内容和错误代码,您可以像在 Spring Boot 中模拟任何其他功能一样模拟一个函数。如果你不知道,我建议你谷歌一下 spring boot 官方文档并阅读测试 spring boot 应用程序的章节,然后尝试编写一个测试,如果你遇到一个特定的错误,你将它与代码一起发布在这里。

标签: spring spring-boot spring-security spring-webflux


【解决方案1】:

我可以通过下面的代码实现这一点。

为 Mock 用户创建了一个基于条件的类。

@ConditionalOnProperty(prefix = "admin.service", value = "security.mode", havingValue = "MOCK")
@EnableWebFluxSecurity
public class MockSecurityConfig {

    @Autowired
    private AppProperties appProps;

    @Bean
    public SecurityWebFilterChain securitygWebFilterChain(final ServerHttpSecurity http) {

        return http.authorizeExchange().pathMatchers("/**").permitAll().and().csrf().disable().build();
    }

    @Bean
    public AuthenticatedPrinciplaProvider mockSecurityPrincipalProvider() {
        return new MockSecurityContextPrincipleProvider(props.getSecurity().getMock());
    }

}

【讨论】:

    猜你喜欢
    • 2020-11-18
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 2019-02-05
    • 2020-06-12
    • 2020-07-18
    • 2019-03-30
    相关资源
    最近更新 更多