英文:
How to write unit test for SpringBoot API having Spring Security configured
问题
我已创建一个包含多个端点的 Spring Boot 应用程序。除了 signup
和登录端点外,我还为其他请求添加了一个过滤器。除此以外的所有请求都应包含:
Authorization
Bearer <token>
这些请求会通过 Spring Security 过滤器链,该链会通过 UserDetailService
检查用户是否存在于表中。
我想知道在已经使用了 Spring Security 的情况下,如何为任何 GET/POST API 编写单元测试?
我脑海中有一种方法,就是通过调用 signup
API 来生成实际的令牌,然后使用由 Signup API 生成的授权令牌调用其他 API。
或者
可能有一些方法可以在单元测试中模拟或跳过授权 Bearer。
我想知道在这种情况下,正确/最佳的方法是什么?
英文:
I have created a Spring Boot application containing various endpoints. Except for signup
and login endpoints I've added a filter for other requests. All other requests should have:
Authorization
Bearer <token>
and requests goes through Spring Security filter chain which checks the user exists in the table or not via UserDetailService
.
I would like to know how can I write unit tests for any GET/POST API with Spring Security in place ?
One way i have in mind is to generate the actual token by calling signup
API and then call other APIs with the Authorization token generated by Signup API.
OR
There might be some way to mock or skip the Authorization Bearer for unit tests
I wanted to know what is this the correct/best approach that's followed across?
答案1
得分: 2
对于我的应用程序,我一直在使用MockUser
注解与MockMvc
bean的组合。MockUser
能够将Spring Security上下文填充为一个用户及其主体,其中包括他的User
对象和GrantedAuthority
(也称为角色)。通过这种方式,您可以在不需要创建任何令牌的情况下测试您的控制器。这样做更加简便,也更加脱离了您的身份验证流程。
示例代码如下:
@Test
@WithMockUser("admin")
void testAuthorize() throws Exception {
this.mockMvc.perform(get("/objects")).andExpect(status().isOk());
}
在Spring文档中,您可以阅读更多关于此的内容。此外,您还可以使用@WithAnonymousUser
来模拟匿名用户,使用@WithUserDetails
来指定自定义的UserDetailsService
。
英文:
For my applications i have been using a conbination of MockUser
annotation with a MockMvc
bean. MockUser
is able to populate Spring SecurityContext with a user and his principal, which includes his User
object and GrantedAuthority
(aka ROLEs). With this you can test your controllers without needing to create any token. It is easier and more decoupled from your autthentication process.
Like this:
@Test
@WithMockUser("admin")
void testAuthorize() throws Exception {
this.mockMvc.perform(get("/objects")).andExpect(status().isOk());
}
In Spring docs you can read more about. And you also have @WithAnonymousUser, to simulate anonnymouser, @WithUserDetails to put a custom UserDetailsService
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论