我正在使用 Spring Boot 1.3、Spring 4.2 和 Spring Security 4.0。我正在使用 MockMvc 运行集成测试,例如:
mockMvc = webAppContextSetup(webApplicationContext).build();
MvcResult result = mockMvc.perform(get("/"))
.andExpect(status().isOk())
.etc;
在我的测试中,我正在模拟这样的用户登录:
CurrentUser principal = new CurrentUser(user);
Authentication auth =
new UsernamePasswordAuthenticationToken(principal, "dummypassword",
principal.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
这适用于我用 注释的方法,@PreAuthorize
例如从测试中调用这样的方法时:
@PreAuthorize("@permissionsService.canDoThisThing(principal)")
public void mySecuredMethod()
原则,我的 CurrentUser 对象,在PermissionsService#canDoThisThing
.
我有一个用 @ControllerAdvice 注释的类,它将当前登录的用户添加到模型中,以便可以在每个视图中访问它:
@ControllerAdvice
public class CurrentUserControllerAdvice {
@ModelAttribute("currentUser")
public CurrentUser getCurrentUser(Authentication authentication) {
if (authentication == null) {
return null;
}
return (CurrentUser) authentication.getPrincipal();
}
}
但是,这在运行应用程序时工作正常(这是我的问题) - 在运行我的测试时,传递给上述 getCurrentUser 方法的身份验证参数始终为空。这意味着在我的视图模板中对 currentUser 属性的任何引用都会导致错误,因此这些测试会失败。
我知道我可以通过检索这样的原则来解决这个问题:
authentication = SecurityContextHolder.getContext().getAuthentication();
但我宁愿不更改我的主要代码,以便测试工作。