Testing Spring Boot Security simply

后端 未结 2 1955
遥遥无期
遥遥无期 2021-02-07 16:10

I\'m struggling with testing access control on URLs protected by Spring Security.

The configuration looks like this:

    http
            .authorizeReque         


        
相关标签:
2条回答
  • 2021-02-07 16:44

    You should not add the FilterChainProxy directly. Instead, you should apply SecurityMockMvcConfigurers.springSecurity() as indicated by the reference. An example is included below:

    mockMvc = MockMvcBuilders
                .webAppContextSetup(context)
                .apply(springSecurity())
                .build();
    

    The result of this is:

    • the FilterChainProxy is added as a Filter to MockMvc (as you did)
    • the TestSecurityContextHolderPostProcessor is added

    Why is TestSecurityContextHolderPostProcessor necessary? The reason is that we need to communicate the current user from the test method to the MockHttpServletRequest that is created. This is necessary because Spring Security's SecurityContextRepositoryFilter will override any value on SecurityContextHolder to be the value found by the current SecurityContextRepository (i.e. the SecurityContext in HttpSession).

    Update

    Remember anything that contains role in the method name automatically prefixes "ROLE_" to the string that was passed in.

    Based on your comment, the problem is you need to either update your configuration to use hasRole instead of hasAuthority (since your annotation is using roles):

    .authorizeRequests()
                .antMatchers("/api/user/**", "/user").authenticated()
                .antMatchers("/api/admin/**", "/templates/admin/**", "/admin/**").hasRole("ADMIN")
                .anyRequest().permitAll();
    

    Alternatively

    You in Spring Security 4.0.2+ you can use:

    @WithMockUser(authorities="ADMIN")
    
    0 讨论(0)
  • 2021-02-07 16:58

    Okay, figured it out.

    mockMvc.perform(get("/api/user/account")
          .with(user("user")))
          .andExpect(status().isOk());
    

    It works now.

    0 讨论(0)
提交回复
热议问题