Тестирование аннотаций PreAuthorize с помощью пользовательских bean-компонентов - PullRequest
0 голосов
/ 18 июня 2020

Я пытаюсь протестировать свои PreAuthorize аннотации в моих методах обслуживания в Spring Boot. Мне удалось заставить его оценить выражения SPeL, однако он не работает при ссылке на пользовательский bean.

Метод обслуживания, который я тестирую:

@PreAuthorize("hasPermission(#eventId.id(), @eventTypePermission.target, @eventTypePermission.write())")
  public EventTypeId retrieveEventTypeIdForEventId(EventId eventId) {
    return null;
  }

Тестовый код:

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
class TestConfig extends GlobalMethodSecurityConfiguration {

  @Override
  protected MethodSecurityExpressionHandler createExpressionHandler() {
    DefaultMethodSecurityExpressionHandler expressionHandler =
      new DefaultMethodSecurityExpressionHandler();
    expressionHandler.setPermissionEvaluator(new PermissionEvaluatorProxyTest());
    return expressionHandler;
  }

  @Bean
  public EventTypePermission permission() {
    return new EventTypePermission();
  }
}

@Component
@Slf4j
class PermissionEvaluatorProxyTest implements PermissionEvaluator {
  @Autowired
  public PermissionEvaluatorProxyTest() {
  }

  @Override
  public boolean hasPermission(
    Authentication authentication, Object targetType, Object permission) {
    return true;
  }

  @Override
  public boolean hasPermission(
    Authentication authentication, Serializable targetId, String targetType, Object permission) {
    return true;
  }
}

@Import({TestConfig.class})
@RunWith(SpringRunner.class)
@SpringBootTest(classes={EventUpdater.class})
public class EventUpdaterTest {
  @Autowired
  private EventUpdater eventUpdater;
  @MockBean
  private EventRepository repository;
  @MockBean
  private EventTypePermission eventTypePermission;

  @Before
  public void setup() {
  }

  @Test
  @WithMockUser(username="test")
  public void test() {
    eventUpdater.retrieveEventTypeIdForEventId(new EventId(UUID.randomUUID()));
  }
}

Ошибка:

java.lang.IllegalArgumentException: Failed to evaluate expression 'hasPermission(#eventId.id(), @eventTypePermission.target, @eventTypePermission.write())'
...
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1057E: No bean resolver registered in the context to resolve access to bean 'eventTypePermission'

Копаться в ней не удается, потому что экземпляр преобразователя bean-компонентов, используемый выражением SPeL, равен нулю. Любые мысли о том, почему это может быть так и как настроить преобразователь bean-компонентов, чтобы он мог возвращать экземпляр EventTypePermission?

. Я также пытался изменить @SpringBootTest(classes={EventUpdater.class}) на @SpringBootTest(classes={EventUpdater.class, EventTypePermission.class}), но безуспешно.

1 Ответ

2 голосов
/ 19 июня 2020

Он заработал, явно установив контекст приложения в классе конфигурации:

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
class TestConfig extends GlobalMethodSecurityConfiguration {
  private ApplicationContext applicationContext;

  @Autowired
  public TestConfig(ApplicationContext applicationContext) {
    this.applicationContext = applicationContext;
  }


  @Override
  protected MethodSecurityExpressionHandler createExpressionHandler() {
    DefaultMethodSecurityExpressionHandler expressionHandler =
      new DefaultMethodSecurityExpressionHandler();
    expressionHandler.setPermissionEvaluator(new PermissionEvaluatorProxyTest());
    expressionHandler.setApplicationContext(applicationContext);
    return expressionHandler;
  }
}

Также пришлось обновить аннотацию SpringTestClass, чтобы включить EventTypePermission: @SpringBootTest(classes={EventUpdater.class, EventTypePermission.class}), а не определять Bean в классе TestConfig.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...