实战技巧:在Spring Security中进行单元测试
今天组里的新人迷茫的问我:哥,Spring Security弄的我单元测试跑不起来,总是401,你看看咋解决。没问题,有写单元测试的觉悟,写的代码质量肯定有保证,对代码质量重视的态度,这种忙一定要帮!
Spring Security 测试环境
要想在单元测试中使用Spring Security,你需要在Spring Boot项目中集成:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
这样测试的上下文配置就能和Spring Security结合起来了,接下来教你几招。
Spring Security 测试
所有的测试都是在Spring Boot Test下进行的,也就是@SpringBootTest
注解的支持下。
@WithMockUser
@WithMockUser
注解可以帮我们在Spring Security安全上下文中模拟一个默认名称为user
,默认密码为password
,默认角色为USER
的用户。当你的测试方法使用了该注解后,你就能通过:
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
获取该模拟用户的信息,也就“假装”当前登录了用户user
。当然你也可以根据需要来自定义用户名、密码、角色:
@SneakyThrows
@Test
@WithMockUser(username = "felord",password = "felord.cn",roles = {"ADMIN"})
void updatePassword() {
mockMvc.perform(post("/user/update/password")
.contentType(MediaType.APPLICATION_JSON)
.content("{\n" +
" \"newPassword\": \"12345\",\n" +
" \"oldPassword\": \"12345\"\n" +
"}"))
.andExpect(ResultMatcher.matchAll(status().isOk()))
.andDo(print());
}
❝当然你可以将
@WithMockUser
标记到整个测试类上,这样每个测试都将使用指定该用户。
@WithAnonymousUser
@WithAnonymousUser
是用来模拟一种特殊的用户,也被叫做匿名用户。如果有测试匿名用户的需要,可以直接使用该注解。其实等同于@WithMockUser(roles = {"ANONYMOUS"})
,也等同于@WithMockUser(authorities = {"ROLE_ANONYMOUS"})
,细心的你应该能看出来差别。
@WithUserDetails
虽然@WithMockUser
是一种非常方便的方式,但可能并非在所有情况下都凑效。有时候你魔改了一些东西使得安全上下文的验证机制发生了改变,比如你定制了UserDetails
,这一类注解就不好用了。但是通过UserDetailsService
加载的用户往往还是可靠的。于是@WithUserDetails
就派上了用场。
@SneakyThrows
@Test
@WithUserDetails("felord")
void updatePassword() {
mockMvc.perform(post("/user/update/password")
.contentType(MediaType.APPLICATION_JSON)
.content("{\n" +
" \"newPassword\": \"12345\",\n" +
" \"oldPassword\": \"12345\"\n" +
"}"))
.andExpect(ResultMatcher.matchAll(status().isOk()))
.andDo(print());
}
当我们执行单元测试时,将通过UserDetailsService
的loadUserByUsername
方法查找用户名为felord
的用户并加载到安全上下文中。
自定义注解
其实我们还可以模拟@WithMockUser
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithSecurityContext(factory = WithMockUserSecurityContextFactory.class)
public @interface WithMockUser {
String value() default "user";
String username() default "";
String[] roles() default { "USER" };
String[] authorities() default {};
String password() default "password";
@AliasFor(annotation = WithSecurityContext.class)
TestExecutionEvent setupBefore() default TestExecutionEvent.TEST_METHOD;
}
关键就在于@WithSecurityContext
注解,我们只需要实现factory
就行了,也就是:
public interface WithSecurityContextFactory<A extends Annotation> {
SecurityContext createSecurityContext(A annotation);
}
这里如法炮制就行,没什么难度就不演示了。
总结
今天介绍了当你的应用中集成了Spring Security时如何单元测试,我们可以使用提供的模拟用户的注解,也可以模拟加载用户,甚至你可以根据自己的需要来定制化。其实如果你使用了JWT的话还有种野路子,你可以在Spring MVC Mock测试中加入对应的请求头或者参数,也能顺利进行。好了今天的分享就到这里,多多关注:码农小胖哥 分享更多的编程知识干货。
推荐阅读
-
实战 Spring Boot:单元测试中的断言技巧
-
实战技巧:在Spring Security中进行单元测试
-
太赞了!这是一份超级无敌的Spring Cloud Alibaba完全指南,几乎覆盖所有操作技巧 - 如果你正在纠结选择哪个Spring Cloud技术栈,那一定要试试官方背书的Spring Cloud Alibaba。作为中国最强大的微服务框架,Spring Cloud Alibaba 在实战中证明了自己的实力,经历过双十一等大促考验,含金量爆棚,如今已经成为国内微服务领域的重量级武器。 关键一点,Spring Cloud Alibaba 很早就获得了Spring Cloud官方的认可和授权。相较于Spring Cloud官方的标准版本,它提供了更全面的功能、更易用的API,并且由于融入了中文支持,使得原本复杂难懂的微服务架构变得更加亲民。实际上,Spring Cloud Alibaba 已经是国内微服务技术领域的默认标杆,正是这一点让我强烈建议大家去学习掌握Spring Cloud Alibaba。
-
南邮OJ Web任务大揭秘:层层挑战剖析 1. 挑战一:迷宫般的目录探索 题目作者似乎穷举了所有可能的目录组合,最终在404.php中的