3

我有一个使用 JHipster 创建的应用程序。我生成了一个博客实体,然后修改了BlogResource类,使其getAll()方法只返回当前用户的博客。

/**
 * GET  /blogs -> get all the blogs.
 */
@RequestMapping(value = "/blogs",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<Blog> getAll() {
    log.debug("REST request to get all Blogs");
    return blogRepository.findAllForCurrentUser();
}

BlogRepositoryfindAllForCurrentUser()方法如下。

@Query("select blog from Blog blog where blog.user.login = ?#{principal.username}")
List<Blog> findAllForCurrentUser();

为了测试这一点,我可以使用 Spring Security 的RequestPostProcessor

@Test
@Transactional
public void getAllBlogs() throws Exception {
    restBlogMockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();

    // Initialize the database
    blog.setUser(userRepository.findOneByLogin("user").get());
    blogRepository.saveAndFlush(blog);

    // Get all the blogs
    restBlogMockMvc.perform(get("/api/blogs").with(user("user")))
        //.andDo(print())
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("$.[*].id").value(hasItem(blog.getId().intValue())))
        .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString())))
        .andExpect(jsonPath("$.[*].handle").value(hasItem(DEFAULT_HANDLE.toString())));
}

我很想知道为什么使用这样的注释@WithMockUser并且@WithUserDetails不会为此工作。如果我将其更改为使用注释,则会收到以下错误:

[DEBUG] org.jhipster.app.security.Http401UnauthorizedEntryPoint - Pre-authenticated entry point called. Rejecting access

java.lang.AssertionError: Status 
Expected :200
Actual   :401
4

0 回答 0