首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >spring boot如何为调度任务设置securitycontext以调用安全方法?

spring boot如何为调度任务设置securitycontext以调用安全方法?
EN

Stack Overflow用户
提问于 2019-05-31 04:48:50
回答 1查看 960关注 0票数 0

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

代码语言:javascript
复制
@Scheduled()
public void update() {
  sync()
}

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

一旦计划任务运行,securityContextnull。在不取消权限验证的情况下,如何设置定时任务的securityContext为Admin?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-31 14:34:04

SecurityContext存储在ThreadLoacal中。您可以使用以下代码创建一个假管理员用户,并在运行sync()之前将其设置为SecurityContext

代码语言:javascript
复制
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中清除这个假管理员用户:

代码语言:javascript
复制
SecurityContextHolder.clearContext();
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56385457

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档