代码之家  ›  专栏  ›  技术社区  ›  Dragonthoughts

JUnit5测试使用Spring安全的安全控制器

  •  0
  • Dragonthoughts  · 技术社区  · 4 年前

    我有一个简单的控制器,只能在安全的环境中访问。 在我的应用程序中,我只将其他网址列入白名单,而不是 /user .

    在单机测试中 @GetResponse 我得到的Http状态为401,而不是200。我希望如此,因为它是安全的。

    当我实际使用登录用户运行应用程序时,我得到一个200的有效结果。

    我如何对请求和任何其他安全控制器路径的行为进行单元测试?

    单元测试:

    @SpringBootTest
    @AutoConfigureMockMvc
    class UserControllerTest {
    
      @InjectMocks
      UserController userController;
      @Autowired
      private MockMvc mockMvc;
      @Autowired
      private ApplicationContext applicationContext;
    
      @Test
      void getUserNone() throws Exception {
    
        mockMvc
            .perform(MockMvcRequestBuilders.get("/user"))
            .andExpect(status().isOk());
      }
    }
    

    应用程序:

    @SpringBootApplication
    public class WebApp extends WebSecurityConfigurerAdapter {
    
      public static void main(final String... args) {
        SpringApplication.run(WebApp.class, args);
      }
    
      @Override
      protected void configure(final HttpSecurity http) throws Exception {
        http
            .authorizeRequests(a -> a
                .antMatchers("/error", "/css/**", "/webjars/**").permitAll()
                .anyRequest().authenticated()
            )
            .exceptionHandling(e -> e
                .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
            )
            .oauth2Login();
      }   
    }
    

    控制器:

    @Controller
    public class UserController {
    
      @GetMapping("/user")
      public @ResponseBody
      Map<String, Object> getUser(@AuthenticationPrincipal final OAuth2User principal) {
        if (principal == null) {
          return Collections.EMPTY_MAP;
        } else {
          return Collections.singletonMap("name", principal.getName());
        }   
      }
    }
    

    显然,我可以补充 /用户 对于白名单中的路径,但对于应用程序的任何安全部分来说,这都是不正确的。

    0 回复  |  直到 4 年前
        1
  •  3
  •   Fausto Carvalho Marques Silva    4 年前

    您可以使用注释 @WithMockUser @WithAnonymousUser 这会制造出假货 Authentication 居住在 SecurityContext . 可以找到文档 here .

    示例代码:

    @Test
    @WithMockUser("john")   
    void testAuthorize() throws Exception {
            mockMvc
               .perform(MockMvcRequestBuilders.get("/user"))
               .andExpect(status().isOk());
    }
    @Test
    @WithAnonymousUser
    void testUnauthorized() throws Exception {
            mockMvc
               .perform(MockMvcRequestBuilders.get("/user"))
               .andExpect(status().isUnauthorized());
    }