Rest – API Auth vs User Auth

apiauthenticationrest

I have read many posts and articles on this topic but still cant connect the dots. I want to make a Rails app that is strictly a JSON API maybe using Sinatra or the rails-api gem. I also want to make both a web client app and an iPhone app which consumes the API. No plans on letting third party dev's use it.

So I could create a separate username/password combination for both the web and mobile client and use HTTP Basic over SSL. Each app would have these values as configs in the source and use it to authenticate to the API so only these can make a call. Anyone else trying would get a 401 error returned. This would be considered handling the API authentication.

The web and mobile client apps allow end users to sign up and read/write data to the API. When each user is created, I create and save a token in their profile. If a user successfully signs in, I send back the token. On each future read/write then also send along this token in the header. I get the token and lookup the user in the database and make the read/write.

Does this sound like an appropriate way to handle it. For the web client, when I initially send back the token, where do I store it. In a cookie? Do I also drop a cookie to handle session state?

Best Answer

I am looking to implement a similar approach. The technologies are different, but the concepts are the same.

Basically, I have:

  • ASP.NET MVC 4 web application, using OAuth (which I think uses the DotNetOpenAuth API)
  • ASP.NET Web API (REST), in same "space" as above, authorization via header token
  • Mobile Device Application, authenticates via OAuth

When the Mobile Device Application authenticates via OAuth, I provide a callback to a method in the Web API which checks that the user exists and has access, and returns a generated token.

Subsequent calls by the Mobile Device Application to the Web API sends the token in the header (over SSL) and thus gets authorized or not per call.

In this case we're not persisting the token beyond the current active session, after which the user would have to authenticate again.

OAuth used in this example, but it could be any other authentication mechanism, which provides a token which would then be used for authorization.

This sounds like the same solution that you're looking at and seems to work fine during some initial testing.

Update: the following is a very good reference for this type of thing: WPF Application With Live ID, Facebook, Google, Yahoo!, Open ID

Related Topic