spring-boot - 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
将计划任务的设置为管理员?
解决方案
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();
推荐阅读
- r - 如何选择仅包含 r 中常见日期的数据?
- python - 在列号是操作数之一的情况下进行操作?
- python - 仪表:无法启动仪表 API:连接到 python #1932 超时
- javascript - 从 JS 值键中获取参数
- merge - 当键可能混合在不同的变量中时,有没有办法在 Stata 中进行合并?
- javascript - 如何使用 updater 和optimisticUpdater 在 Relay 中更新 store 和 UI?
- google-forms - 访问谷歌表单属性以创建自定义表单样式?
- python - 似乎无法在 ubuntu 20.04 Visual Studio 代码上安装 Fbprophet
- qt - Qt/QML - 手动移动处理程序和调整窗口大小后的拆分视图行为
- excel - 当我单击登录按钮时,我试图打开另一个表单,要查看的数据在工作表上。我得到的错误是在 set shtTeam