首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Spring Security @Secured注解测试Spring Boot @WebFluxTest

如何使用Spring Security @Secured注解测试Spring Boot @WebFluxTest
EN

Stack Overflow用户
提问于 2021-04-13 20:36:20
回答 1查看 654关注 0票数 1

我在测试由Spring Security的@Secured注解保护的Spring WebFlux控制器时遇到了麻烦。下面是我的控制器代码:

代码语言:javascript
复制
@RestController
@RequestMapping("/endpoint")
public class MyController {

    @GetMapping()
    @Secured("ADMIN")
    public Flux<MyOutputDto> getOutputDtos() {
        return myService.getOutputDtos();
    }
}

下面是我的测试代码:

代码语言:javascript
复制
@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文档和在线文章,但都没有成功。

有人有这方面的想法吗?提前感谢

EN

回答 1

Stack Overflow用户

发布于 2021-04-14 17:20:34

好了,我搞清楚是怎么回事了。

首先,Spring Security似乎没有为响应式应用程序(即Spring WebFlux)处理@Secured注释。对于@EnableReactiveMethodSecurity,您必须使用@PreAuthorize注释。

然后,我必须创建一个测试配置并将其导入到我的测试中,它就像一个护身符一样工作。

代码语言:javascript
复制
@TestConfiguration
@EnableReactiveMethodSecurity
public class WebFluxControllerSecurityTestConfig {
}
代码语言:javascript
复制
@WebFluxTest(MyController.class)
@Import(WebFluxControllerSecurityTestConfig.class)
class MyControllerTest {

  // Same tests

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67075009

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档