我正在尝试使用@scheduled任务来更新我的数据库中的一些数据。
@Scheduled()
public void update() {
sync()
}
public void sync() {
if (SecurityContextHolder.getContext()
.getAuthentication().getAuthorities().stream.matchAny(r-> ROLE_ADMIN)) {
...
} else {
...
}
}一旦计划任务运行,securityContext为null。在不取消权限验证的情况下,如何设置定时任务的securityContext为Admin?
发布于 2019-05-31 14:34:04
SecurityContext存储在ThreadLoacal中。您可以使用以下代码创建一个假管理员用户,并在运行sync()之前将其设置为SecurityContext:
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//This is the permission that the admin should have. It depends on your application security configuration.
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
// Here it does not matter what values username and password are.
// Just ensure this user has the the Admin GrantedAuthority and his account is enabled
User user = new User("admin", "password", true, true, true, true, grantedAuthorities);
Authentication authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);如果执行sync()的线程专用于计划的任务,那么您可以让该线程拥有这个假的管理员用户。否则,您需要在运行ThreadLocal ()之后从sync中清除这个假管理员用户:
SecurityContextHolder.clearContext();https://stackoverflow.com/questions/56385457
复制相似问题