akz08
akz08

Reputation: 45

API Authentication and use of OAuth2

I’m trying to get my head around how I would introduce token-based (key-based?) authentication to a web API (currently looking at Sinatra, but maybe Rails too) that would be used by a mobile client and how OAuth would fit into the picture.

So, let’s say I want to create a web service that uses Facebook for authentication and grabbing basic user data. Here, my API would be a client to Facebook’s OAuth Server, requesting an access token upon a user’s successful login to Facebook. This would then grant me access to the user’s data which I would use to create an entry in my database, storing this user-specific token with any other application information I would like linked to them.

I think I got that part right so far, but here’s where I’m a bit confused.

I think that my API would also need some form of API key to grant access to a mobile user, since I wouldn’t want to transmit and store the Facebook key on their device. Would I have to have a separate store of keys which I provide to the client to access my service? Are there any ‘best practice’ ways of doing this?

Upvotes: 2

Views: 520

Answers (1)

dre-hh
dre-hh

Reputation: 8044

Would I have to have a separate store of keys which I provide to the client to access my service?

yes.

Are there any ‘best practice’ ways of doing this?

The simplest way would be to generate a separate authentication token on every User creation and expose that to the mobile client. Then send it with every subsequent request header.

Devise provides a simple example how to achieve that. You don't need devise for that, just provide some token generation mechanism.

#Devise.friendly_token
def self.friendly_token
  SecureRandom.urlsafe_base64(15).tr('lIO0', 'sxyz')
end

This mechanism can be extended to provide more security in following ways

  1. Being an oauth2 provider itself. On successfull login with facebook, you would generate an :authorization_code which the client can exchange for your own Oauth2 Bearer or MAC token within a next step. Then you can send your own Oauth2 token with every request for user authentication. See rack-oauth2

  2. Implement HMAC token encryption. Generate and expose a secret_key to every client after singning in. Use this secret to sign messages along with a unique client id. The server can then lookup the secret_key for the specific client_id and verify the message.
    See api-auth

Upvotes: 2

Related Questions