Spring Security 实战干货:Spring Security中的单元测试

举报
码农小胖哥 发表于 2022/04/14 00:32:43 2022/04/14
【摘要】 今天组里的新人迷茫的问我:哥,Spring Security弄的我单元测试跑不起来,总是401,你看看咋解决。没问题,有写单元测试的觉悟,写的代码质量肯定有保证,对代码质量重视的态度,这种忙一定要帮! Spring Security 测试环境 要想在单元测试中使用Spring Security,你需要在Spring B...

今天组里的新人迷茫的问我:哥,Spring Security弄的我单元测试跑不起来,总是401,你看看咋解决。没问题,有写单元测试的觉悟,写的代码质量肯定有保证,对代码质量重视的态度,这种忙一定要帮!

Spring Security 测试环境

要想在单元测试中使用Spring Security,你需要在Spring Boot项目中集成:


   
  1.         <dependency>
  2.             <groupId>org.springframework.security</groupId>
  3.             <artifactId>spring-security-test</artifactId>
  4.             <scope>test</scope>
  5.         </dependency>

这样测试的上下文配置就能和Spring Security结合起来了,接下来教你几招。

Spring Security 测试

所有的测试都是在Spring Boot Test下进行的,也就是@SpringBootTest注解的支持下。

@WithMockUser

@WithMockUser注解可以帮我们在Spring Security安全上下文中模拟一个默认名称为user,默认密码为password,默认角色为USER的用户。当你的测试方法使用了该注解后,你就能通过:


   
  1.  Authentication authentication = SecurityContextHolder.getContext()
  2.             .getAuthentication();

获取该模拟用户的信息,也就“假装”当前登录了用户user。当然你也可以根据需要来自定义用户名、密码、角色:


   
  1. @SneakyThrows
  2. @Test
  3. @WithMockUser(username = "felord",password = "felord.cn",roles = {"ADMIN"})
  4. void updatePassword() {
  5.     mockMvc.perform(post("/user/update/password")
  6.             .contentType(MediaType.APPLICATION_JSON)
  7.             .content("{\n" +
  8.                     "  \"newPassword\": \"12345\",\n" +
  9.                     "  \"oldPassword\": \"12345\"\n" +
  10.                     "}"))
  11.             .andExpect(ResultMatcher.matchAll(status().isOk()))
  12.             .andDo(print());
  13. }

当然你可以将@WithMockUser标记到整个测试类上,这样每个测试都将使用指定该用户。

@WithAnonymousUser

@WithAnonymousUser是用来模拟一种特殊的用户,也被叫做匿名用户。如果有测试匿名用户的需要,可以直接使用该注解。其实等同于@WithMockUser(roles = {"ANONYMOUS"}),也等同于@WithMockUser(authorities = {"ROLE_ANONYMOUS"}),细心的你应该能看出来差别。

@WithUserDetails

虽然@WithMockUser是一种非常方便的方式,但可能并非在所有情况下都凑效。有时候你魔改了一些东西使得安全上下文的验证机制发生了改变,比如你定制了UserDetails,这一类注解就不好用了。但是通过UserDetailsService 加载的用户往往还是可靠的。于是@WithUserDetails就派上了用场。


   
  1. @SneakyThrows
  2. @Test
  3. @WithUserDetails("felord")
  4. void updatePassword() {
  5.     mockMvc.perform(post("/user/update/password")
  6.             .contentType(MediaType.APPLICATION_JSON)
  7.             .content("{\n" +
  8.                     "  \"newPassword\": \"12345\",\n" +
  9.                     "  \"oldPassword\": \"12345\"\n" +
  10.                     "}"))
  11.             .andExpect(ResultMatcher.matchAll(status().isOk()))
  12.             .andDo(print());
  13. }

当我们执行单元测试时,将通过UserDetailsServiceloadUserByUsername方法查找用户名为felord的用户并加载到安全上下文中。

自定义注解

其实我们还可以模拟@WithMockUser


   
  1. @Target({ ElementType.METHOD, ElementType.TYPE })
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Inherited
  4. @Documented
  5. @WithSecurityContext(factory = WithMockUserSecurityContextFactory.class)
  6. public @interface WithMockUser {
  7.    String value() default "user";
  8.    String username() default "";
  9.    String[] roles() default { "USER" };
  10.  
  11.    String[] authorities() default {};
  12.  
  13.    String password() default "password";
  14.  
  15.    @AliasFor(annotation = WithSecurityContext.class)
  16.    TestExecutionEvent setupBefore() default TestExecutionEvent.TEST_METHOD;
  17. }

关键就在于@WithSecurityContext注解,我们只需要实现factory就行了,也就是:


   
  1. public interface WithSecurityContextFactory<A extends Annotation> {
  2.  
  3.    SecurityContext createSecurityContext(A annotation);
  4. }

这里如法炮制就行,没什么难度就不演示了。

总结

今天介绍了当你的应用中集成了Spring Security时如何单元测试,我们可以使用提供的模拟用户的注解,也可以模拟加载用户,甚至你可以根据自己的需要来定制化。其实如果你使用了JWT的话还有种野路子,你可以在Spring MVC Mock测试中加入对应的请求头或者参数,也能顺利进行。好了今天的分享就到这里,多多关注:码农小胖哥 分享更多的编程知识干货。

封装了一个Excel导入加校验的工具,同事们用了都说好

2021-04-20

Spring Security 实战干货:WebSecurity和HttpSecurity的关系

2021-04-19

文章来源: felord.blog.csdn.net,作者:码农小胖哥,版权归原作者所有,如需转载,请联系作者。

原文链接:felord.blog.csdn.net/article/details/116077844

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。