【问题标题】:Add @PreAuthorize role for spring schedule job为春季计划作业添加@PreAuthorize 角色
【发布时间】:2019-07-23 00:53:50
【问题描述】:
在我的后端,我添加了@PreAuthorize("hasRole('ROLE_ADMIN') 以允许用户访问服务层中的功能。现在我想使用我的调度作业(springframework 调度)来访问这些服务,但是显然不能。我的问题是如何添加 ROLE_ADMIN 角色或为计划作业生成用户主体?
@PreAuthorize("hasRole('ROLE_ADMIN')")
JsonNode loadSMS(String additionalPath) {
.....
}
【问题讨论】:
标签:
java
spring
spring-boot
spring-security
【解决方案1】:
要么有另一种方法没有用你的调度程序调用的@PreAuthorize 注释。将实现移到这个新方法中,并将现有的loadSMS 更改为使用这个新方法以减少代码重复。否则你可以在运行时添加一个角色,但我认为这不是一个好主意。
【解决方案2】:
你可以试试下面的代码
@Service
class SchedulerService {
@Autowired
private YourService service;
@Scheduled(fixedRate = 600000L, initialDelay = 60000L)
public void executeTask() throws IOException {
RunAs.runAsAdmin(() -> {
service.loadSMS(String additionalPath) {
});
}
}
public class RunAs {
@FunctionalInterface
public interface RunAsMethod {
default void run() {
try {
runWithException();
} catch (Exception e) {
}
}
void runWithException() throws Exception;
}
public static void runAsAdmin(final RunAsMethod func) {
final AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("adminUser", "adminPassword",
ImmutableList.of(new SimpleGrantedAuthority("ROLE_ADMIN")));
final Authentication originalAuthentication = SecurityContextHolder.getContext().getAuthentication();
SecurityContextHolder.getContext().setAuthentication(token);
func.run();
SecurityContextHolder.getContext().setAuthentication(originalAuthentication);
}
}