You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring与Jobrunr权限校验:Job中手动认证用户可行吗?

问题:Jobrunr任务中调用服务层权限校验崩溃,能否手动认证用户?

我正在开发一个包含4种角色的应用,数据库中仅存储角色,无权限信息:

  • 控制器层通过如下方式限制路由仅对特定角色开放:
@PreAuthorize("hasRole('ADMIN')")
  • 服务层方法中会根据需求进行更细致的权限校验,但这些校验仅在SecurityContextHolder.getContext()不为空时生效。

目前遇到的问题:在Jobrunr的Job中调用服务方法时,SecurityContextHolder.getContext()为空,导致调用崩溃。请问是否可以在Job中手动认证用户?这种方式是否可行?


更新(针对@Ken Chan的回复 - 代码无法运行)

Jobrunr Job代码:

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class InactiveUsersEmail implements JobRequest {
    private Integer userId;

    @Override
    public Class<InactiveUsersEmailHandler> getJobRequestHandler() {
        return InactiveUsersEmailHandler.class;
    }
}

尝试使用DelegatingSecurityContextRunnable运行的代码:

Stream<DelegatingSecurityContextRunnable> jobs = this.userService
    .findAll()
    .map(user -> {
        Runnable task = () -> new InactiveUsersEmail(user.getId());
        return new DelegatingSecurityContextRunnable(task, this.authorizationComponent.getSecurityContext());
    });

// 此处报错:
// cannot resolve method 'enqueue(java.util.stream.Stream<org.springframework.security.concurrent.DelegatingSecurityContextRunnable>)'
BackgroundJobRequest.enqueue(jobs);

内容的提问来源于stack exchange,提问作者Jedupont

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 08:24:59