spring boot如何为调度任务设置安全上下文以调用安全方法?

时间:2019-05-30 20:48:50

标签: spring-boot spring-security scheduled-tasks

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

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

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

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

1 个答案:

答案 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();