#Spring authorization

10 messages · Page 1 of 1 (latest)

stiff scaffold
#

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

placid harborBOT
#

This post has been reserved for your question.

Hey @stiff scaffold! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

finite silo
#

Is there a reason this is being run in a Job Queue? findById feels like it should be short enough to do in a normal manner

placid harborBOT
#

💤 Post marked as dormant

This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.

stiff scaffold
#

Now that makes me wonder, is this a good way to do authorization at the service layer? Is it better for the controller?

shut kestrel
#

you don't generally need authorization if the job is supposed to be triggered internally

finite silo
finite silo
#

@stiff scaffold Alternatively you can include a User Reference in the Schedule, so you'd refactor to include that User Reference, and check against that reference when the schedule runs.