I was recently playing around with an idea – a proof of concept – for an mobile app API. If you’ve never done this before, keep reading.
The high-level requirements:
- A mobile app that you have control over
- An API you’re working on
- Users must be authenticated
As I am the app and API owner, I thought it best and easiest to use a two-legged OAuth implementation – username & password plus some secret keys (3-legged vs 2-legged explanation). This is what your users will expect when logging into your app & service. Before you can start, find an appropriate library for your web framework. There are plenty out there, so pick your poison. I’m familiar and develop relatively quickly with CakePHP, so I went with seddonmeida cakephp-oauth-server. I’ll spare you from too much code.
First, you’ll have to set up an OAuth client in the database. This is for your app and nobody else. Follow your library’s instructions; you’ll find out you can’t read values from the database because they should be hashed. Once you have it installed and are sure it’s working, you can start the setup. In the CakePHP plugin,
$client = $this->OAuth->Client->add('myapp://register'); //the URL isn't really important in this case
Save your client_id and client_secret in a safe place. You’ll need it in your app. Now, the fun part. You can test this in your browser, but it will work the same way in your app.
First, Grant the Token
In OAuth terms, we’re doing a password type grant with the client_id and client_secret.
You’ll get JSON in return with a few important keys, namely access_token and refresh_token. They will serve as your ID badge for future requests. Keep them around. NB: access_token is used most, but refresh_token has a special place.
Making a request for protected resources is easy. Assuming your back-end is set up properly, you should be able to run something like this with no problem:
I know the above URL is at /oauth/, but that doesn’t mean your entire API has to be handled with your OAuth controller. In practice, you should include your OAuth library as a component of each appropriate controller wherever you’re accessing the API, or at least secured content.
Refreshing Your Token
A lot of services using OAuth aren’t going to expire your token. Seddonmeida’s implementation uses an expiration, but in practice doesn’t actually enforce it; that’s up to you. In the case you do have an expiring token, it’s best to refresh your user’s keys from time to time so they aren’t “logged out.” To get a fresh new token, access our OAuth token action and request a refresh_token grant type using the client_id, client_secret, and the refresh_token you received when first authenticating.
A Note About HTTPS
Make these requests over HTTPS if you have any option at all. Otherwise, HTTP is sending your username and password over in cleartext, which we all know isn’t a great idea.