我想在一个测试中测试一组具有不同角色的用户对方法的访问。我正在尝试像这样更改登录用户:
@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 (...))总是从ALL_ROLES_USERS数组中的第一个用户执行。这可以从日志中看出:
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?我不知道在哪里挖了