I'm developing a Spring application with roles . I do my role checks on my controllers with @PreAuthorize("hasRole('ADMIN')") for example and sometimes I need more advanced conditions than just the role.
I've got into the habit of putting all this logic into the service, for example here to access a contract :
public Contract findById(int id) {
return this.contractRepository.findById(id)
.map(contract -> {
if (!this.authorizationComponent.canEditContract(contract)) {
throw new CustomException(null, HttpStatus.UNAUTHORIZED);
}
return contract;
}).orElseThrow(() -> new CustomException("Contract doesn't exist", HttpStatus.NOT_FOUND));
}
}
My problem is that I use Jobrunr to dispatch jobs in a queue and when in this job I want to call my service's method, I get an error because the SecurityContextHolder is null. I don't have an authenticated user, so it's impossible to check the SecurityContextHolder role.
Jobrunr: https://github.com/jobrunr/jobrunr