Selvaraj
Selvaraj

Reputation: 726

How to control response property based on roles in RestAPI?

We are trying to implement RestAPI with user access control, where same URI should return different response for two user having different roles. Say, response for the URI(/resource/123)

{
    "customer_name":"user_name", #String
    "location":"000", #String
    "age":30 #Int
    "has_submitted_tax":true #Boolean
}

How to hide each property based on roles.

Approach 1:

Hiding the node which shouldn't be accessed by the user

Problem: This will break the response structure. Client might break, as an expected node gets missed out.

Approach 2:

Returning null for that node.

Problem: This will break the response data type. As a 'boolean' node will have null value.

Approach 3:

Returning default value for that node.

Problem: Here the node will have some value, where there is an equal chance of the actual value being returned for the node.(default value being the actual value)

Upvotes: 0

Views: 59

Answers (1)

David Brossard
David Brossard

Reputation: 13834

There is no right or wrong answer. It all depends on the contract between the client and the service. When you define your contract for e.g. getCustomer(), then that contract would stipulate that either

  1. Some values may be an empty string, or
  2. the mask value is xxx, or
  3. the field may not be present at all (akin to optional elements in XML)

That summarizes your 3 approaches. So long as the client is aware of which strategy you went for, then it is fine.

If you are applying authorization to an existing API with a large number of clients that expect a certain behavior, then your best option is to go for masked values where the values are replaced w/ a default value. The risk there is not so much that the default value may be the real one but rather that the end user is not aware that information has been masked.

Upvotes: 1

Related Questions