Restricting API Access to User-Created Resources

authenticationrest

What is the best practice way to restrict access to particular resources based on ownership. For example, if Adam created several posts (collection: /posts). And I want Adam to be the only user able to GET these, how can I restrict another user, Eve, from retrieving Adam's posts from the data store?

I can force a user to authenticate, to access /posts/*, however I'm not sure what the best way is to implement ownership?

I could create an 'owns' connection between user and the entity, and have some business logic which checks the relationship once the entity is retrieved before returning a response to the requesting app, but this would entail an additional call.

Is there a better way to restrict access to entities based on ownership?

Best Answer

You are mixing two different topics: Authentication and Authorization.


Authentication

Authentication is the act of confirming the truth of an attribute of a single piece of data claimed true by an entity or as identification, which refers to the act of stating or otherwise indicating a claim purportedly attesting to a person or thing's identity, being the authentication the process of actually confirming that identity.

This answers the question: Who are you?


Authorization

Authorization is the function of specifying access control applying rights to a resource. More formally, "to authorize" is to define an access policy.

This aspect answers the question: What can you do with this resource?


As you can see, for you to do the Authorization phase you first must do the Authentication.

As an example, i'm authenticated right now in this site but i'm not authorized to delete your question. This is because i first passed on the Authentication phase - so the site knows who i am - and when i accessed your question, the site knows that i don't have admin rights, so it won't let me delete questions. - Authorization Phase.


In your scenario

As an REST API, you will have some form of authentication. This you have to choose for yourself, but in the end of it you have an authenticated user - or Principal. For more information on REST API authentication see the discussion on StackOverflow.

With the information of the authenticated user - that you can extract of the http request - all you have to do is check if the authenticated user has the authorization to do what it is requesting. In your case, check if he is the author of the resource he is trying to GET.

Related Topic