Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement authentication for REST API?

I'm creating a web based service that I want to expose as a REST API so that developers are able to create apps using it. I want developers to be able to create/manage user accounts and authenticate through API. How to handle this? OAuth or something else?

I'm using python,flask,mongodb for this.

like image 662
anujkk Avatar asked Jul 16 '12 07:07

anujkk


Video Answer


1 Answers

We have settled on the following, using OAuth 2 (which is much preferable to OAuth 1). In particular we are using the resource owner password credentials flow. As to how to integrate it into our RESTful service, here is the idea:

  • The initial resource, when hit by an unauthorized user, returns a 401. The body of the 401 contains a single link, with rel=oauth2-token. (How you signal links depends on your media type; we're using HAL, but you could use even just the Link header.)
  • After the user authenticates, he returns to the initial resource, sending in his Authorization header the bearer token returned from the OAuth 2 process. At this point, we return a 200, with all the normal links available.

We don't expose account creation, but if you wanted to do that, I would do so with another link available to unauthorized users in the initial resource. That link would have a custom rel since it is specific to your application, e.g. rel=http://rels.myapi.com/users

Good RESTful design would indicate that the link with this rel points to e.g. http://myapi.com/users, and that consumers of the API do a POST to that endpoint, which returns to them the new user resource with a Location header pointing to the newly-created user resource at e.g. http://myapi.com/users/username. (User resources themselves would of course be another rel, distinguishing between the singular user resource and the plural users collection resource.)

like image 100
Domenic Avatar answered Sep 23 '22 17:09

Domenic