如何为实现了Spring安全性的SpringBoot API编写单元测试

问题描述 投票:1回答:1

我创建了一个包含各种端点的SpringBoot应用程序。除了注册和登录端点外,我还为其他请求添加了过滤器。所有其他请求应具有

[Authorization Bearer <token>

并且请求通过spring安全过滤器,该过滤器通过UserDetailService检查用户是否存在于表中。

我想知道如何在安装了Spring Security的情况下为任何GET / POST API编写单元测试?

我想到的一种方法是通过调用注册API生成实际令牌,然后使用由注册API生成的授权令牌来调用其他API。

OR

可能有某种方法可以模拟或跳过UnitTests的授权载体

我想知道遵循的正确/最佳方法是什么?

java spring spring-boot junit spring-security
1个回答
0
投票

对于我的应用程序,我一直在使用MockUser注释与MockMvc bean的组合。 MockUser可以用用户及其主体填充Spring SecurityContext,其中包括其User对象和GrantedAuthority(又名ROLE)。这样,您就可以测试控制器,而无需创建任何令牌。与您的认证过程更加容易且脱钩。

喜欢这个:

@Test
@WithMockUser("admin")  
void testAuthorize() throws Exception {
    this.mockMvc.perform(get("/objects")).andExpect(status().isOk());
}

在Spring文档中,您可以阅读更多about。您还可以使用@WithAnonymousUser模拟匿名鼠标,@WithUserDetails放置自定义UserDetailsService

© www.soinside.com 2019 - 2024. All rights reserved.