【发布时间】:2020-05-04 05:03:37
【问题描述】:
这里是一个简单的类,从 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 mockwebserver 运行的应用程序。
【问题讨论】:
标签: spring-security okhttp spring-webflux spring-test