10

我有一个 Spring Boot 应用程序,它需要登录才能执行某些操作。我正在尝试使用 测试它们MockMvc,但它似乎不起作用。我不断收到状态为 403(禁止)的 HTTP 响应。身份验证部分可能有问题。

我已尝试按照文档进行操作,但无法使其正常工作。

这是我当前的测试代码:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
@WebIntegrationTest("server.port = 8093")
public class PasswordChangeTests {
    @Autowired
    private EmbeddedWebApplicationContext webApplicationContext;

    @Autowired
    private UserRepository userRepository;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        this.mockMvc = MockMvcBuilders
                .webAppContextSetup(webApplicationContext)
                .apply(springSecurity())
                .build();
    }

     @Test
     public void changePasswordWorks() throws Exception {
         // Send password change request
         PasswordChangeRepresentation passwordChange = new PasswordChangeRepresentation(DefaultUsers.Admin.getPassword(), "12345678");
         mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.POST, "/password/change")
                 .content(new ObjectMapper().writeValueAsString(passwordChange))
                 .contentType(MediaType.APPLICATION_JSON)
                 .accept(MediaType.APPLICATION_JSON))
                 .andExpect(status().isOk());

         // Check that the password has been changed
         User user = this.userRepository.findByUsername(DefaultUsers.Admin.getEmail());
         Assert.assertEquals(user.getPassword(), "12345678");
    }
}

抱歉,如果我遗漏了一些明显的东西。这是我第一次体验spring boot。

4

1 回答 1

27

您需要指定要以哪个用户身份运行测试。您有几个选项(每个选项都是详细文档的链接):

@WithMockUser

此选项将创建一个假用户(即该用户不需要存在于数据存储中)。这种方法的问题是,如果您的应用程序依赖于自定义用户实现,您可能会遇到类强制转换异常。如果您不从自定义 UserDetailsS​​ervice 返回自定义类型,则此解决方案应该可以正常工作。

 @Test
 @WithMockUser(username="admin",roles={"USER","ADMIN"})
 public void changePasswordWorks() throws Exception {

@WithUserDetails

如果您实现了一个返回 UserDetails 的自定义实现的自定义 UserDetailsS​​ervice,则此解决方案可能适合您。

要使其工作,您需要将 UserDetailsS​​ervice 公开为 Bean,并且用户必须存在。例如:

 @Test
 @WithUserDetails("admin")
 public void changePasswordWorks() throws Exception {

@WithSecurityContext

这是两全其美的方法,但需要一些额外的设置。如果您有自定义 UserDetailsS​​ervice 返回 UserDetails 的自定义实现并且不希望用户必须存在,您可以使用此方法。我会让您阅读有关此设置的文档,因为它有点冗长且有据可查。

使用 RequestPostProcessor

如果注释不是你的事,你可以使用 RequestPostProcessor。例如:

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;

 ...

 @Test
 public void changePasswordWorks() throws Exception {
     // Send password change request
     PasswordChangeRepresentation passwordChange = new PasswordChangeRepresentation(DefaultUsers.Admin.getPassword(), "12345678");
     mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.POST, "/password/change")

             // ADD this line
             .with(user("admin").roles("USER","ADMIN"))

             .content(new ObjectMapper().writeValueAsString(passwordChange))
             .contentType(MediaType.APPLICATION_JSON)
             .accept(MediaType.APPLICATION_JSON))
             .andExpect(status().isOk());

     // Check that the password has been changed
     User user = this.userRepository.findByUsername(DefaultUsers.Admin.getEmail());
     Assert.assertEquals(user.getPassword(), "12345678");
}
于 2015-04-17T16:52:57.167 回答