我在测试由Spring Security的@Secured注解保护的Spring WebFlux控制器时遇到了麻烦。下面是我的控制器代码:
@RestController
@RequestMapping("/endpoint")
public class MyController {
@GetMapping()
@Secured("ADMIN")
public Flux<MyOutputDto> getOutputDtos() {
return myService.getOutputDtos();
}
}下面是我的测试代码:
@WebFluxTest(MyController.class)
class MyControllerTest {
@Autowired
WebTestClient webTestClient;
@Test
@WithApplicationUser(roles = "ADMIN")
void should_work_fine() {
webTestClient.get()
.uri("/endpoint")
.exchange()
.expectStatus().isOk();
}
@Test
void should_return_401_unauthorized() {
webTestClient.get()
.uri("/endpoint")
.exchange()
.expectStatus().isUnauthorized();
}
@Test
@WithApplicationUser
void should_return_403_forbidden() {
webTestClient.get()
.uri("/endpoint")
.exchange()
.expectStatus().isForbidden();
}
}@WithApplicationUser注释是一个自定义注释,它使用提供的角色在安全上下文中注入模拟身份验证对象。如果没有提供角色(就像在第三个测试中一样),那么它将缺省为根本没有角色。
这里的问题是,前两个测试运行良好,但第三个测试失败,返回200OK而不是403禁止。我的第一个想法是Spring Security没有处理@Secured注释,所以我阅读了许多Spring WebFlux/Spring Security文档和在线文章,但都没有成功。
有人有这方面的想法吗?提前感谢
发布于 2021-04-14 17:20:34
好了,我搞清楚是怎么回事了。
首先,Spring Security似乎没有为响应式应用程序(即Spring WebFlux)处理@Secured注释。对于@EnableReactiveMethodSecurity,您必须使用@PreAuthorize注释。
然后,我必须创建一个测试配置并将其导入到我的测试中,它就像一个护身符一样工作。
@TestConfiguration
@EnableReactiveMethodSecurity
public class WebFluxControllerSecurityTestConfig {
}@WebFluxTest(MyController.class)
@Import(WebFluxControllerSecurityTestConfig.class)
class MyControllerTest {
// Same tests
}https://stackoverflow.com/questions/67075009
复制相似问题