How to model restrictions on data visible on resou

2019-08-01 16:27发布

问题:

How to model restrictions on data visible on resources? Different people are accessing the same resources but with different roles so they are not allowed to see all the information.

The case I am working on:
Solution without access restriction on information:

User:
  name
  phoneNumber

If anyone could access it this would be easy to model as:

GET /User -> [{name:"John", phoneNumber: "322-333"}]
GET /User/{id} -> {name:"John", phoneNumber: "322-333"}

However, say I have two roles, admin and user. The phoneNumber must only be visible to users who are also admins. Authorization token is transmitted in a cookie, header or similar. The server will know which roles a requester has. How would one design an API to handle this? I have a couple of ideas:

1) The naive solution would be to just filter it and leave the fields unset if you arent allowed to access it ie.

If user: GET /User -> [{name:"John"}]
If admin: GET /User -> [{name:"John", phoneNumber: "322-333"}]

2) Embed the role in the url:

If user is wanted as a User: GET /User/User -> [{name:"John"}]
If user is wanted as an Admin: GET /Admin/User -> [{name:"John", phoneNumber: "322-333"}]

3) Define a new resource for each possible subset of fields:

If user is wanted as a User:   GET /PublicUserInfo -> [{name:"John"}]
If user is wanted as an Admin: GET /FullUserInfo -> [{name:"John", phoneNumber: "322-333"}]

Would a different approach be better ?
Does anyone have experience with a solution that worked out in practice?

回答1:

Use option 1 based on the authenticated user. If you opt for 2 or 3 clients implementing your API have to worry about twice as any API endpoints and when they should be used.



标签: api rest