如何绕过RestController上的Spring @PreAuthorize注释进行测试?

时间:2018-06-11 15:39:16

标签: spring spring-boot spring-security pcfdev

如何创建旁路 @Preauthorize 以便我可以在本地测试而不调用实际因为注释将在类加载之前加载?

@RestController
@RequestMapping("/test")
public class ResourceController {
    @RequestMapping(method = GET)
    @PreAuthorize
    @ResponseBody
    public String message(){ return "Hello World"; }

2 个答案:

答案 0 :(得分:0)

您可以在代码中拥有一个测试配置文件,然后在针对代码运行测试时激活该配置文件。然后,您可以在测试中使用预定义的用户和密码。

@Configuration
public class TestConfig {

  @EnableWebSecurity
  @Profile("test")
  class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService() {
      InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
      manager.createUser(User.withUsername("user").password("password").roles("ROLE1", "ROLE2", "ROLE3").build());
      return manager;
    }
  }
}

答案 1 :(得分:0)

您可以使用spring-security-test来实现。

pom.xml

<dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-test</artifactId>
      <version>5.3.3.RELEASE</version>
      <scope>test</scope>
    </dependency>

假设您的控制器如下所示:

@PreAuthorize("hasRole('ROLE_ADMIN')")
  public User createUser(final User user) {
    ......
  }

您的测试如下所示:

public class MyControllerTests {

  private MockMvc mvc;
  
  @BeforeEach
  void setup() {
    
    mvc = MockMvcBuilders
        .webAppContextSetup(context)
        .apply(springSecurity())
        .build();
  }

  @Test
  void testCreateWithProperPermission() throws Exception {
    
    final User user = new User();
    user.setName("Test");

    final MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post("/v1/foo/").with(user("foo").roles("ADMIN"))
        .content(new ObjectMapper().writeValueAsString(user))
        .contentType(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        
    final String responseBody = mvcResult.getResponse().getContentAsString();

    final User created = new ObjectMapper().readValue(responseBody, User.class);

    // verify the saved entity's data is correct
    assertThat(created).isNotNull();
    assertThat(created)
        .hasFieldOrPropertyWithValue("name", user.getName());

  }