这里是一个简单的类,它从spring安全上下文中读取Principal用户:
public Mono<Void> getAndCheckAccessRights(Integer agencyKey) {
return ReactiveSecurityContextHolder.getContext()
.map(securityContext -> getAccessRights(agencyKey, securityContext.getAuthentication().getName()))
.switchIfEmpty(Mono.defer(() -> {
log.error("No security context found!");
throw new AuthorizationException("No security context found!");
}))
.flatMap(accessRightsDtoMono -> checkAccessRights(accessRightsDtoMono))
.then();
}
private Mono<AccessRightsDto> getAccessRights(Integer agencyKey, String bensl) {
return dataServiceWebClient.get()
.uri("/access_rights/" + agencyKey + "/" + bensl)
.retrieve()
.bodyToMono(AccessRightsDto.class)
.switchIfEmpty(Mono.defer(() -> {
log.error("No user found!");
throw new AuthorizationException("No user found!");
}));
}
虽然测试它不应该执行的操作,但是执行只是跳过代码行而无需执行.map或.flatMap中的方法流,日志未打印,并且在任何级别上都没有调试日志,测试只是在一切正常终止时才运行,我不知道为什么会发生这种情况:
@WebFluxTest(AccessRightService.class)
...
@Test
@WithMockUser
void getAndCheckAccessRights_NOT_AUTHORIZED() throws JsonProcessingException {
AccessRightsDto testAccessRightsDto = AccessRightsDto
.builder(123456789, "test", "test", PUBLISH, PUBLISH, PUBLISH, PUBLISH, PUBLISH,
PUBLISH, PUBLISH, PUBLISH, NO_ACCESS)
.build();
MockResponse response = new MockResponse();
response.setResponseCode(HttpStatus.OK.value()).setBody(objectMapper.writeValueAsString(testAccessRightsDto));
mockWebServer.enqueue(response);
assertThrows(AuthorizationException.class, () -> accessRightService.getAndCheckAccessRights(123456789));
}
当然,在运行应用程序时,它仅能按预期正常工作,测试很奇怪!
使用Spring Boot 2.2.2和okhttp3模拟网络服务器运行的应用程序。
[我不好,我忘了在传播获取对象的输入的.block()
之后放getAndCheckAccessRights
,尽管什么也不会发生。
实际上还不清楚在Netty情况下如何工作,因为它不接受.block()
,但是在测试中可以调用它。