@Scheduled触发时,在SecurityContext中找不到身份验证对象吗?

时间:2019-10-19 20:03:08

标签: java spring spring-boot spring-security spring-scheduled

我创建了一个Spring Boot应用,遇到了一些可以手动触发或通过@Scheduled注释触发的端点。

我遇到的问题是以下问题:

  

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException:   在SecurityContext中找不到身份验证对象

如果通过SecurityContext调用了该过程,是否可以触发@Scheduled

我是Spring Security的新手,很难理解参考指南。我发现了一些类似的问题,但仍然无法理解如何对我的案子应用答案。

我的MyController的示例:

@Secured("ROLE_ADMIN")
@RestController
@RequestMapping(value = "/api")
public class MyController {

    @Scheduled(cron = "* * * * * *")
    @GetMapping(path="/data")
    public void getData() {
        // Do some operations
    }
}

2 个答案:

答案 0 :(得分:2)

@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
    }
}

答案 1 :(得分:1)

基本上,您必须使用必要的身份验证来配置调度程序。以下内容:

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')")注释控制器。