Spring boot Как установить securitycontext для запланированной задачи для вызова защищенного метода? - PullRequest
0 голосов
/ 30 мая 2019

Я пытаюсь использовать задачу @scheduled для обновления некоторых данных в моей базе данных.

@Scheduled()
public void update() {
  sync()
}

public void sync() {
   if (SecurityContextHolder.getContext()
      .getAuthentication().getAuthorities().stream.matchAny(r-> ROLE_ADMIN)) {
...
    } else {
    ...
    }
}

securityContext - это null после запуска запланированной задачи. Не удаляя проверку прав доступа, как мне установить securityContext запланированной задачи на Admin?

1 Ответ

0 голосов
/ 31 мая 2019

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);

Если поток, выполняющий синхронизацию (), выделен для запланированной задачи натолько для запуска, вы можете оставить этот поток для этого фальшивого администратора.В противном случае вам нужно очистить этого фальшивого администратора от ThreadLocal после запуска sync ():

SecurityContextHolder.clearContext();
...