0

If you use the hasAuthority or hasRole functions you can use @WithMockUser in your tests. However if I use access there is no way to use @WithMockUser with the correct user object.

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

How can I write a test for a controller that is protected with the above HttpSecurityConfig? What I need is to create a fake UserDetail object that is used in the exchange (I think). I use Webflux.

UPDATE: This is the manager i want to use:

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));
        });
  }
}
user3139545
  • 6,882
  • 13
  • 44
  • 87
  • Can you share the manager you use in `.access()`? There is nothing preventing `@WithMockUser` from being used with `.access()`. If you need to add additional attributes to the mocked user, that would depend on what your access restriction is. – Eleftheria Stein-Kousathana Dec 19 '19 at 11:48
  • Added exact impl. – user3139545 Dec 19 '19 at 16:54
  • Thank you for adding the implementation. Correct me if I am wrong, but your question looks similar to https://stackoverflow.com/questions/52861849/withmockuser-with-custom-user-implementation/57093952#57093952. Let me know if that helps. – Eleftheria Stein-Kousathana Dec 20 '19 at 13:14
  • Does this answer your question? [@WithMockUser with custom User implementation](https://stackoverflow.com/questions/52861849/withmockuser-with-custom-user-implementation) – user3139545 Dec 22 '19 at 08:52

0 Answers0