我有类似Spring Boot的服务
@GetMapping("/myService")
@PreAuthorize("hasAnyAuthority('EDIT')")
public String savePermissionList(...) {
....
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Integer roleId = null;
if (authentication.getDetails() instanceof MyRole) {
roleId = (((MyRole) authentication.getDetails()).getId());
}
}
我需要此服务来保存以后需要的权限列表。由于我想测试其他服务,因此我需要在测试的一开始就运行此方法。我以为我可以使用这样的东西:
@Before
public void setUp() throws Exception {
role1 = new MyRole(....)
MockitoAnnotations.initMocks(this);
final Authentication authentication = mock(Authentication.class);
final SecurityContext securityContext = mock(SecurityContext.class);
when(securityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(securityContext);
when(authentication.getDetails()).thenReturn(role1);
final ArrayList<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("EDIT"));
when((List<GrantedAuthority>) authentication.getAuthorities()).thenReturn(authorities);
...
savePermissionList(...);
但是我面临的问题是错误消息:
org.springframework.security.authentication.ProviderNotFoundException: No AuthenticationProvider found for org.springframework.security.core.Authentication$MockitoMock$1249720784