【发布时间】:2020-07-11 09:35:11
【问题描述】:
上下文:我创建了一个测试注释@WithMockAuthentication 来使用Authentication 实例填充测试安全上下文,就像@WithMockUser 所做的那样。
主要区别在于,在我的例子中,实例是一个 Mockito 模拟。
我的经验:一旦我用模拟替换实际实例,作为控制器方法参数提供的 Authentication 实例在带注释的测试中为空:在 WithSecurityContextFactory 中,如果我替换:
public Authentication workingAuthentication(WithMockAuthentication annotation) {
return new TestAuthentication(annotation.name(), Stream.of(annotation.authorities()).map(SimpleGrantedAuthority::new).collect(Collectors.toSet()));
}
与
public Authentication bogousAuthentication(WithMockAuthentication annotation) {
var auth = mock(Authentication.class);
when(auth.getName()).thenReturn(annotation.name());
when(auth.getAuthorities()).thenReturn((Collection) Stream.of(annotation.authorities()).map(SimpleGrantedAuthority::new).collect(Collectors.toSet()));
when(auth.isAuthenticated()).thenReturn(true);
return auth;
}
然后我在控制器测试中得到 NPE
@RequestMapping("/method")
@PreAuthorize("hasRole('ROLE_AUTHORIZED')")
public ResponseEntity<String> securedMethod(Authentication auth) {
// Here, auth is null if Authentication is a mock
return ResponseEntity.ok(String.format("Hey %s, how are you?", auth.getName()));
}
我创建了一个minimal sample to reproduce。运行测试看看失败。
我很确定我遇到了一个错误。够创建an issue in spring-security project了,不过Spring团队好像没时间调查了……
[编辑] 最后这句话是无用的冒犯性和完全错误的,因为答案是由 Spring-security 的主要成员 Rob Winch 提供的:/我的坏
【问题讨论】:
标签: spring-mvc spring-security spring-test-mvc