在这种情况下,手动解决方法是一个选项:
(1) 如果这是一项独立的工作,
在调用安全方法之前,创建一个 Authentication 对象并将其设置为安全上下文。在安全方法执行完成后,从安全上下文中删除 Authentication 对象。
public final class AuthenticationUtil {
//Ensures that this class cannot be instantiated
private AuthenticationUtil() {
}
public static void clearAuthentication() {
SecurityContextHolder.getContext().setAuthentication(null);
}
public static void configureAuthentication(String role) {
Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(role);
Authentication authentication = new UsernamePasswordAuthenticationToken(
"user",
role,
authorities
);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
所以它看起来像
AuthenticationUtil.configureAuthentication(role);
// Call to the secured method
AuthenticationUtil.clearAuthentication();
(2) 对于 web 应用,我们不能将 authentication 对象设为 null,不要调用
AuthenticationUtil.configureAuthentication(role);
// call to the secured method