2015-05-29 22 views
19

Tôi cần gửi yêu cầu nhận API, nhưng mặc dù đã đặt chú thích quản trị gặp lỗi@WithMockUser(roles="ADMINISTRADOR").
Tôi làm cách nào để gửi yêu cầu?

APIKiểm tra tích hợp với bảo mật mùa xuân

@RequestMapping(value = "/{id}", method = RequestMethod.GET) 
@PostAuthorize("returnObject.instancia == principal.instancia.instancia") 
public Validacao retrieve(@PathVariable("id") String id) { 
    return validacaoService.retrieve(id); 
} 

thử nghiệm

@Test 
@WithMockUser(roles = "ADMINISTRADOR") 
public void testCRetrieve() throws Exception { 
     this.mockMvc 
       .perform(get("/api/validacao/" + id).with(user("[email protected]"))) 
       .andExpect(status().isOk()) 
       .andReturn(); 
} 

Log

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext 

Kiểm tra Lớp

@FixMethodOrder(MethodSorters.NAME_ASCENDING) 
@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = {ValidacaoAPITest.TestConfiguration.class, WithSecurityConfig.class}) 
@WebAppConfiguration 
public class ValidacaoAPITest { 
    @EnableWebMvc 
    @Configuration 
    public static class TestConfiguration { 
     Fongo fongo = new Fongo("new server 1"); 
     DB db = fongo.getDB("oknok"); 

     @Bean 
     ValidacaoAPI getValidacaoAPI() { 
      return new ValidacaoAPI(); 
     } 

     @Bean 
     ActiveUser getActiveUser() { 
      ActiveUser mock = Mockito.mock(ActiveUser.class); 

      when(mock.getUser()).thenReturn(new User().setEmail("[email protected]")); 
      when(mock.getInstancia()).thenReturn(new Instancia().setInstancia("instancia")); 
      return mock; 
     } 

     @Bean 
     ValidacaoService getValidacaoService() { 
      return new ValidacaoService(); 
     } 

     @Bean 
     MatchService getMatchService() { 
      return new MatchService(); 
     } 

     @Bean 
     PlanilhaReader getPlanilhaReader() { 
      return new PlanilhaReader(); 
     } 


     @Bean 
     AtributoReader getAtributoReader() { 
      return new AtributoReader(); 
     } 

     @Bean 
     AtributoDAO getAtributoDAO() { 
      return new AtributoDAO(); 
     } 

     @Bean 
     UploadService getUploadService() { 
      return new UploadService(); 
     } 


     @Bean 
     ValidacaoResultadoDAO getValidacaoResultadoDAO() { 
      return new ValidacaoResultadoDAO(db); 
     } 


     @Bean 
     Mapper getMapper() { 
      return new Mapper(db); 
     } 

     @Bean 
     UploadDAO getUploadDAO() { 
      return new UploadDAO(db); 
     } 

     @Bean 
     MatchDAO getMatchDAO() { 
      return new MatchDAO(db); 
     } 

     @Bean 
     ValidacaoDAO getValidacaoDAO() { 
      return new ValidacaoDAO(db); 
     } 

     @Bean 
     UploadOriginalsDAO getUploadOriginalsDAO() { 
      return new UploadOriginalsDAO(db); 
     } 

     @Bean 
     AtributoValidator getAtributoValidator() { 
      return new AtributoValidator(); 
     } 

    } 

    @Autowired 
    MatchService matchService; 

    @Autowired 
    private WebApplicationContext context; 

    private MockMvc mockMvc; 

    private static String id; 

    @Before 
    public void setup() { 
     mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); 
    } 

    @Test 
    public void testACreateValidation() throws Exception { 
     MvcResult result = this.mockMvc 
       .perform(post("/api/validacao")) 
       .andExpect(status().isOk()) 
       .andExpect(jsonPath("$.id", notNullValue())) 
       .andReturn(); 
     this.id = ((BasicDBObject) JSON.parse(result.getResponse().getContentAsString())).getString("id"); 
    } 

    @Test 
    public void testBRetrieveAll() throws Exception { 
     MvcResult result = this.mockMvc 
       .perform(get("/api/validacao")) 
       .andExpect(status().isOk()) 
       .andExpect(jsonPath("$.[0].id", notNullValue())) 
       .andReturn(); 

     BasicDBList list = (BasicDBList) JSON.parse(result.getResponse().getContentAsString()); 
     this.id = (String) ((BasicDBObject) JSON.parse(list.get(0).toString())).get("id"); 
    } 

    //FIXME 
    @Test 
    @WithMockUser(roles = "ADMINISTRADOR") 
    public void testCRetrieve() throws Exception { 
      this.mockMvc 
        .perform(get("/api/validacao/" + id).with(user("[email protected]"))) 
        .andExpect(status().isOk()) 
        .andReturn(); 
    } 

} 
+0

bạn đã sử dụng WithSecurityContextTestExcecutionListener chưa? Bạn có thể cung cấp lớp kiểm tra hoàn chỉnh không? – coder

+0

Bạn có vai trò đánh máy, @WithMockUser (vai trò = "ADMINISTRADOR"), nó phải là @WithMockUser (roles = "ADMINISTRATOR") –

Trả lời

23

Trong an ninh mùa xuân Reference, section 10.1 nói rằng để có thể kiểm tra các tính năng bảo mật mùa xuân, bạn cần phải tích hợp chuỗi bộ lọc bảo mật trong đối tượng MockMvc của bạn, như được hiển thị trong ví dụ này trong phương pháp @Trước khi thiết lập.

import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*; 

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration 
@WebAppConfiguration 
public class CsrfShowcaseTests { 

    @Autowired 
    private WebApplicationContext context; 
    private MockMvc mvc; 

    @Before 
    public void setup() { 
     mvc = MockMvcBuilders 
      .webAppContextSetup(context) 
      .apply(springSecurity()) 
      .build(); 
    } 

... 

} 
+0

Quên đề cập đến, cụ thể hơn, đó là nếu bạn muốn tích hợp các kiểm tra bảo mật mùa xuân với khung kiểm tra mvc mùa xuân, nếu bạn không muốn sử dụng khung kiểm tra mvc mùa xuân, điều này là không cần thiết. – saljuama

+0

Trong các phiên bản trước của bảo mật mùa xuân, phương pháp này hoạt động: http://stackoverflow.com/questions/23335200/spring-boot-setup-security-for-testing – Shannon

Các vấn đề liên quan