Spring从@Scheduled任务调用安全方法
我使用的是SpringBoot1.5.3、SpringSecurity、SpringJPA和Hibernate。 我有几个使用安全注释的存储库: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
@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