在HttpSecurityConfig上使用访问控制时,WithMockUser不起作用

时间:2019-12-19 07:43:38

标签: java spring-security spring-webflux

如果使用hasAuthorityhasRole函数,则可以在测试中使用@WithMockUser。但是,如果我使用access,则无法对正确的用户对象使用@WithMockUser

@Bean
public HttpSecurityConfig securityConfiguration() {
    return http -> {
        http.authorizeExchange()
            .pathMatchers(HttpMethod.GET, "/api/**")
            .access(<ReactiveAuthorizationManager>));
    };
}

如何为受以上HttpSecurityConfig保护的控制器编写测试?我需要创建一个用于交换的伪UserDetail对象(我认为)。我使用Webflux。

更新: 这是我要使用的管理器:

public class ModuleActionAuthorization implements ReactiveAuthorizationManager<AuthorizationContext> {

  private final Module module;
  private final Action action;
  private final Brand brand;

  public ModuleActionAuthorization(Module module, Action action, Brand brand) {
    this.module = module;
    this.action = action;
    this.brand = brand;
  }

  public ModuleActionAuthorization(Module module, Action action) {
    this(module, action, null);
  }

  @Override
  public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, AuthorizationContext ignored) {
    return authentication
        .map(a -> {
          CustomUserDetails userDetails = (CustomUserDetails) a.getPrincipal();
          return new AuthorizationDecision(userDetails.hasAuthorityForAnyBrand(module, action));
        });
  }
}

0 个答案:

没有答案