I'm facing a difficulty where I need to restrict the scope of a request to a specific user's data only. Having an API where a previous authenticated user can retrieve a data list, I first need to validate if the requested data is owned by the requester.
For example, a user with id 1 could only retrieve a subset of data where the owner is, in fact, the one with id 1. Calling to /api/elements/{elementId}
with a previous authenticated user should only return a element with the provided elementId
IF the user who did the request is its owner or IF the user who did the request has an ADMIN
role (or any other granted role). In any other case should return null
or a 404
HTTP status.
After researching for a while, I've got this approach:
Use the user ID in every CRUD operation: this approach forces to check if the current element is owned by the user who did the request.
Pros: I can assure that only the data owned by that user will be read/written
Cons: I need to add the user id in ALL the queries and also restricting the data returned, excluding from this condition a user with role ADMIN
who can query everything without any restriction.
I'm using Spring Boot with Spring Security and JWT for authentication/authorization. Everything works fine, but having this restriction have made me think in some sort of Framework solution (if possible) instead the approach commented above.
How would you approach this problem to solve this restriction with these conditions?
Links related to this issue but with a no specific solution to my case:
- Restricting user to their own data
- API - Restricting Access to Resources the Authenticated User Created
- How to Limit REST API to User-Specific Content
- How to allow a User only access their own data in Spring Boot / Spring Security?
Thank you in advance!