Spring security 如何使用ReactiveSecurityContactExholder进行WebFluxTest
下面是一个从spring安全上下文读取主要用户的简单类:Spring security 如何使用ReactiveSecurityContactExholder进行WebFluxTest,spring-security,okhttp,spring-webflux,spring-test,Spring Security,Okhttp,Spring Webflux,Spring Test,下面是一个从spring安全上下文读取主要用户的简单类: public Mono<Void> getAndCheckAccessRights(Integer agencyKey) { return ReactiveSecurityContextHolder.getContext() .map(securityContext -> getAccessRights(agencyKey, securityContext.getAuthenticatio
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!");
}));
}
当然,当运行应用程序时,它只是按照预期正常工作,测试很奇怪
运行spring boot 2.2.2和okhttp3 mockwebserver的应用程序。我的错,我忘了在
getAndCheckAccessRights
之后放置.block()
,它传播获取对象的输入,而不会发生任何事情
实际上,对于Netty,它是如何工作的还不太清楚,因为它不接受.block()
,但在测试中可以调用它
@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));
}