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

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

[[395171]]

今天组里的新人迷茫的问我:哥,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.  
  6.     mockMvc.perform(post("/user/update/password"
  7.             .contentType(MediaType.APPLICATION_JSON) 
  8.             .content("{\n" + 
  9.                     "  \"newPassword\": \"12345\",\n" + 
  10.                     "  \"oldPassword\": \"12345\"\n" + 
  11.                     "}")) 
  12.             .andExpect(ResultMatcher.matchAll(status().isOk())) 
  13.             .andDo(print()); 

当然你可以将@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.  
  6.     mockMvc.perform(post("/user/update/password"
  7.             .contentType(MediaType.APPLICATION_JSON) 
  8.             .content("{\n" + 
  9.                     "  \"newPassword\": \"12345\",\n" + 
  10.                     "  \"oldPassword\": \"12345\"\n" + 
  11.                     "}")) 
  12.             .andExpect(ResultMatcher.matchAll(status().isOk())) 
  13.             .andDo(print()); 

当我们执行单元测试时,将通过UserDetailsService 的loadUserByUsername方法查找用户名为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.  
  8.    String value() default "user"
  9.  
  10.    String username() default ""
  11.  
  12.    String[] roles() default { "USER" }; 
  13.   
  14.    String[] authorities() default {}; 
  15.   
  16.    String password() default "password"
  17.   
  18.    @AliasFor(annotation = WithSecurityContext.class) 
  19.    TestExecutionEvent setupBefore() default TestExecutionEvent.TEST_METHOD; 
  20.  

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

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

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

总结

 

今天介绍了当你的应用中集成了Spring Security时如何单元测试,我们可以使用提供的模拟用户的注解,也可以模拟加载用户,甚至你可以根据自己的需要来定制化。其实如果你使用了JWT的话还有种野路子,你可以在Spring MVC Mock测试中加入对应的请求头或者参数,也能顺利进行。

 

责任编辑:武晓燕 来源: 码农小胖哥
相关推荐

2021-04-19 07:33:04

WebSecuritySpringHttpSecurit

2021-01-28 09:50:29

分布式对象SharedObjec

2021-05-31 07:18:46

SpringSecurity信息

2019-11-22 09:40:40

SpringJava编程语言

2013-06-04 09:49:04

Spring单元测试软件测试

2021-09-01 12:03:49

Spring单元测试

2021-08-29 18:36:57

项目

2022-11-26 00:00:02

2020-09-16 08:07:54

权限粒度Spring Secu

2021-06-07 14:06:19

Spring SecuCSRF防御

2023-04-10 11:41:15

2022-05-05 10:40:36

Spring权限对象

2009-06-18 14:18:23

Spring secu

2022-01-26 00:05:00

接口Spring管理器

2022-08-15 08:45:21

Spring权限控制

2022-08-30 08:36:13

Spring权限控制

2022-08-30 08:55:49

Spring权限控制

2022-08-15 08:42:46

权限控制Spring

2022-08-30 08:43:11

Spring权限控制

2022-06-16 10:38:24

URL权限源代码
点赞
收藏

51CTO技术栈公众号