Max
Max

Reputation: 1488

Spring Boot REST: Filter results depending on user role

I am building a rest backend with authentication and different roles. Now the problem is, that I like to filter, the result depending on the user role.

I don't have implemented the controller myself, instead, I am using the PagingAndSortingRepository Inferface, this is working pretty well. What I am looking for is something similar to this python-django method.

The solution must conform to the REST pattern.

To make this clearer, here is an example:

Let’s say I have two users, user A is a normal user with the role "user". User B is an admin with the role "admin".

There is a Database table, in which the userData are stored. The table looks like the following.

| ID | username | name | email |

Both of them are sending a simple authenticated GET request to /userData.

Now my backend detects based on the authentication header the users and add the roles.

Now depending on the role, the user A should only get an answer which contains his personal data, user B should get all data which are accessible through /userData.

Response for user A:

{
   "res":[
      {
         "id":1,
         "username":"userA",
         "name":"A",
         "email":"[email protected]"
      }
   ]
}

Response for user B:

{
   "res":[
      {
         "id":1,
         "username":"userA",
         "name":"A",
         "email":"[email protected]"
      },
      {
         "id":2,
         "username":"userB",
         "name":"B",
         "email":"[email protected]"
      },
      {
         "id":3,
         "username":"userC",
         "name":"C",
         "email":"[email protected]"
      }
   ]
}

Upvotes: 2

Views: 2757

Answers (1)

Selindek
Selindek

Reputation: 3423

I created an extension for Spring-Data-Jpa which can handle these kind of requirements (+ a lot more). spring-data-jpa-acl

You can set up rules by roles or associations with a few simple annotations and all of the data-jpa methods and REST endpoints will be affected by these rules. The extension adds extra specifications to JPA queries so all filtering will happen in the DB side, so you can even use pagination on filtered data.

Upvotes: 1

Related Questions