ruby-on-railsruby-on-rails-4rails-api

Rails API : Best way to implement authentication?


I'm writing a Rails 4 app that will expose an API for a mobile app that's yet to be developed. Users will authenticate using an e-mail and password from the mobile app.

While I've found quite a bit of information on the topic. It's hard to discern what's dated or non-optimal. I've read about HTTP Basic Auth, which doesn't seem too secure, and HTTP Token-based Auth, but I'm not sure on how to couple that with regular e-mail and password authentication (I'm using Devise by the way).

I'd just like to know what's the current best practice on how to implement this, so I'll be sure to be going the right way.


Solution

  • The important point, from a security perspective, is to exchange the user's email and password for a token once, and then use that token for subsequent requests. This is because:

    1. You don't want the client app to be responsible for holding onto the user's password, where a bug or attack could cause it to be leaked; and
    2. A server-issued token gives you (and your users) the ability to expire a token if necessary, e.g. to lock out a stolen device or block a misbehaving API client.

    There are many ways to accomplish this with varying levels of complexity.

    Here is a tutorial that is very recent and has a thorough walkthrough for creating an API in Rails with token-based authentication (not using Devise, but still relevant to understand the concepts): https://labs.kollegorna.se/blog/2015/04/build-an-api-now/