I have a few methods in my spring application, that execute sensitive operations on data that should only be invoked by specific roles.
For example, QUOTA_ADMIN
can invoke (via @RestController
) the following
interface WorkspaceQuotaManager {
@PreAuthorize("hasRole('QUOTA_ADMIN')")
void resetWorkspaceQuota(int workspaceNumber);
}
Now, if possible, I’d also want some of these methods to be executed as @Scheduled
, or from @EventListener
but the problem is that there’s no security context in these threads by default.
Is there a (clean) way to make sure when @Scheduled
or @EventListener
are executed they have a specific role? I’ve found a few solutions where you manually add an authentication to the context SecurityContextHolder.getContext().setAuthentication(authentication)
but I’d prefer something a bit less imperative if possible.