在测试中更改授权用户

Change authorized user in tests

我想在一次测试中测试一组具有不同角色的用户对方法的访问。我正在尝试像这样更改登录用户:

@Test
void allMenusAuthorizePermissions() throws Exception {

        for (User user : ALL_ROLES_USERS) {
            Authentication authentication = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities());
            SecurityContextHolder.clearContext();
            SecurityContextHolder.getContext().setAuthentication(authentication);

            log.debug("User role: " + user.getAuthorities());

            if (user == ADMIN || user == EDITOR) {
                perform(get(MenuEditorController.MENU_EDITOR_URL).principal(authentication))
                        .andExpect(status().isOk());
            }else{
                perform(get(MenuEditorController.MENU_EDITOR_URL).principal(authentication))
                        .andExpect(status().isForbidden());
            }

        }
}

但无论我多么努力,perform(get (...)) 总是从 [=28= 的第一个用户开始执行]数组。从日志中可以看出:

o.s.s.a.i.a.MethodSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@e74255f0: Principal: +79990200001; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: CLIENT

-每次迭代都是同一个用户!

知道为什么会这样吗?也许 perform(get(...)) 正在传递第一个用户的 JSESSIONID ?我不知道去哪里挖了

您需要使用:

@Test
    void allMenusAuthorizePermissions() throws Exception {

        for (User user : ALL_ROLES_USERS) {
            log.debug("User role: " + user.getAuthorities());

            if (user == ADMIN || user == EDITOR) {
//              perform(get(MenuEditorController.MENU_EDITOR_URL).with(SecurityMockMvcRequestPostProcessors.user(user.getUsername()).authorities(user.getAuthorities())))
                perform(get(MenuEditorController.MENU_EDITOR_URL).with(SecurityMockMvcRequestPostProcessors.user(user)))
                        .andExpect(status().isOk());
            }else{
                perform(get(MenuEditorController.MENU_EDITOR_URL).with(SecurityMockMvcRequestPostProcessors.user(user)))
                        .andExpect(status().isForbidden());
            }

        }
    }

How to Mock the security context in Spring MVC for testing