我正在尝试使用@scheduled
任务来更新数据库中的某些数据。
@Scheduled()
public void update() {
sync()
}
public void sync() {
if (SecurityContextHolder.getContext()
.getAuthentication().getAuthorities().stream.matchAny(r-> ROLE_ADMIN)) {
...
} else {
...
}
}
计划任务运行后,securityContext
为null
。在不删除权限验证的情况下,如何将计划任务的securityContext
设置为Admin?
答案 0 :(得分:0)
SecurityContext
存储在ThreadLoacal
中。您可以使用以下代码创建伪造的admin用户,然后在运行SecurityContext
之前将其设置为sync()
:
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()的线程专用于计划运行的任务,则可以将该线程保留为该假管理员用户。否则,您需要在运行sync()之后从ThreadLocal
清除该假管理员用户:
SecurityContextHolder.clearContext();