Я пытаюсь использовать задачу @scheduled для обновления некоторых данных в моей базе данных.
@Scheduled()
public void update() {
sync()
}
public void sync() {
if (SecurityContextHolder.getContext()
.getAuthentication().getAuthorities().stream.matchAny(r-> ROLE_ADMIN)) {
...
} else {
...
}
}
securityContext появляется null после запуска запланированной задачи. Без удаления проверки разрешения, как мне установить securityContext запланированной задачи на администратора?




SecurityContext хранится в ThreadLoacal. Вы можете использовать следующие коды, чтобы создать поддельного пользователя-администратора и установить для него SecurityContext перед запуском sync():
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//This is the permission that the admin should have. It depends on your application security configuration.
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
// Here it does not matter what values username and password are.
// Just ensure this user has the the Admin GrantedAuthority and his account is enabled
User user = new User("admin", "password", true, true, true, true, grantedAuthorities);
Authentication authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
Если поток, выполняющий sync(), предназначен только для запуска запланированной задачи, вы можете сохранить этот поток для этого поддельного пользователя-администратора. В противном случае вам нужно удалить этого поддельного пользователя-администратора из ThreadLocal после запуска sync() :
SecurityContextHolder.clearContext();