I have a Spring web service where users only have access to specific resources. Any user can make a request to get the resource info, but I need to throw an Authorization exception if they don't have access to that resource. The API is as follows:
GET /resources/{resourceId}
The above API provides the user all info about a given resource.
Currently I do authentication using WebSecurityConfigurerAdapter
. To add authorization, I have observed that I can set the granted authorities as part of the Authentication object. On doing so, I can use something like @PreAuthorize("hasRole('ROLE_USER')")
to do the authorization.
However, for the mentioned API I am not sure if the mentioned authorization approach is suitable for the following reasons.
- I am authorizing based on the whether the user has privileges to access the specific
resourceId
. This is not exactly a Role. More like a Privilege. Is it still acceptable to usehasRole()
for this use case? - If I did use the
hasRole()
annotation I would need to do something like@PreAuthorize("hasRole('ACCESS_RESOURCEID12346')")
whereRESOURCEID12346
is theresourceId
. But, we only have access toresourceId
once we are in the API controller. So, how do I use that value for the authorization annotation?
If the specified approach is not the best way of solving the problem, I would appreciate any input/feedback on what would be the best approach. I'd like to avoid doing this check in the controller. I am trying to do it through Spring Security similar to how @PreAuthorize works. I think access to the resourceId is an authorization requirement and we should not even get into the API controller if the user doesn't have access to that resource.