首页 > 解决方案 > spring boot如何为调度任务设置securitycontext以调用安全方法?

问题描述

我正在尝试使用@scheduled任务来更新我的数据库中的一些数据。

@Scheduled()
public void update() {
  sync()
}

public void sync() {
   if (SecurityContextHolder.getContext()
      .getAuthentication().getAuthorities().stream.matchAny(r-> ROLE_ADMIN)) {
...
    } else {
    ...
    }
}

securityContext计划null任务运行后。在不删除权限验证的情况下,如何securityContext将计划任务的设置为管理员?

标签: spring-bootspring-securityscheduled-tasks

解决方案


SecurityContext存储在ThreadLoacal. 您可以使用以下代码创建一个假管理员用户并将其设置为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() 的线程专用于仅运行计划任务,您可以让该线程拥有这个假管理员用户。否则,您需要ThreadLocal在运行 sync() 后清除此假管理员用户:

SecurityContextHolder.clearContext();

推荐阅读