2 回答
TA贡献1804条经验 获得超8个赞
基本上,您必须使用必要的身份验证来配置您的调度程序。大致如下:
import com.google.common.collect.ImmutableList;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.concurrent.DelegatingSecurityContextScheduledExecutorService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import java.util.List;
import java.util.concurrent.Executor;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static org.springframework.security.core.context.SecurityContextHolder.getContext;
@Configuration
public class SchedulerConfiguration implements SchedulingConfigurer {
private static final String KEY = "spring";
private static final String PRINCIPAL = "spring";
private static final List<SimpleGrantedAuthority> AUTHORITIES = ImmutableList.of(new SimpleGrantedAuthority("ADMIN"));
@Override
public void configureTasks(final ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
}
@Bean
public Executor taskExecutor() {
final AnonymousAuthenticationToken token = new AnonymousAuthenticationToken(KEY, PRINCIPAL, AUTHORITIES);
final SecurityContext securityContext = getContext();
securityContext.setAuthentication(token);
return new DelegatingSecurityContextScheduledExecutorService(newSingleThreadScheduledExecutor(), securityContext);
}
}
然后你可以用 注释你的控制器@Secured("hasAuthority('ADMIN')")。
TA贡献1784条经验 获得超9个赞
方法@Scheduled不应该@Secured。预定的方法已经在可信代码中。
重构你的代码,例如
@Secured("ROLE_ADMIN")
@RestController
@RequestMapping(value = "/api")
public class MyController {
@Autowired
private MyService myService;
@PostMapping(path="/run")
public void runJobs() {
myService.runJobs();
}
}
@Service
public class MyService {
@Scheduled(cron = "* * * * * *")
public void runJobs() {
// Do some operations
}
}
添加回答
举报