Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring从@Scheduled任务调用安全方法_Spring_Spring Boot_Spring Security - Fatal编程技术网

Spring从@Scheduled任务调用安全方法

Spring从@Scheduled任务调用安全方法,spring,spring-boot,spring-security,Spring,Spring Boot,Spring Security,我使用的是SpringBoot1.5.3、SpringSecurity、SpringJPA和Hibernate。 我有几个使用安全注释的存储库: @Transactional @PreAuthorize("isAuthenticated()") public interface DailyCodeRepository extends PagingAndSortingRepository<DailyCode, Long> { @Query("SELECT MAX(date) FROM

我使用的是SpringBoot1.5.3、SpringSecurity、SpringJPA和Hibernate。 我有几个使用安全注释的存储库:

@Transactional
@PreAuthorize("isAuthenticated()")
public interface DailyCodeRepository extends PagingAndSortingRepository<DailyCode, Long> {

@Query("SELECT MAX(date) FROM DailyCode d ")
public LocalDate findLastCodeDate();

@Query("SELECT COUNT(d) FROM DailyCode d WHERE code=:code AND date>=DATE(:date)")
public long countDailyCodesByCodeGreaterThanDate(@Param("code") @RequestParam(value = "code", required = true) String code,
        @Param("date") @RequestParam(value = "untdateil", required = true) Instant date);
}
现在,当任务启动时,我遇到了一个异常,因为Spring在SecurityContext中找不到身份验证

8/07/2017 14:39:00,007 ERROR pool-3-thread-1 TaskUtils$LoggingErrorHandler:95 - Unexpected error occurred in scheduled task.
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
当然,这并不奇怪。我想知道解决这个问题的最佳做法是什么

  • 创建一个不需要身份验证的服务似乎有些过分。当我已经在存储库中准备好了一个方法时,我必须创建很多代码
  • 通过编程设置安全认证:看起来不错,但安全吗?我发现了一篇旧文章

  • 如果选项2是最好的,我想知道Spring 4.3.x使用的最佳实践。

    Spring安全性实际上是围绕HTTP请求而设计的,而不是独立的方法保护。是的,您可以手动填充安全上下文,但是您必须有一个特殊用户来执行计划任务。我建议您将
    @PreAuthorize
    移动到控制器层,HTTP请求在此终止。谢谢@Abhijit Sarkar,实际上我对您建议的方法使用PreAuthorize。为了在我发布的代码中进行符号化,我删除了它。再次感谢
    8/07/2017 14:39:00,007 ERROR pool-3-thread-1 TaskUtils$LoggingErrorHandler:95 - Unexpected error occurred in scheduled task.
    org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext