Ruby on Rails and Android Authentication Part One
The Rails Web Application
Intro
In this two-three-part tutorial you’ll learn first how to build an authentication API that can allow external users to register, login and logout through JSON requests. After having successfully logged in, a user will receive an authentication token that could be used in following API requests to authorize the user, securing the access to your application’s resources.
In the second part, you will build an Android application that will be able to consume this API, allowing the user to register and login directly from the app.
With these tutorials I want to explain, with a step-by-step approach, how to build a complete solution that can be used as a base for a more complex scenario.
Supplemental bonuses will be given to enhance both the backend and the Android app with additional nice-to-have features.
Let’s start!
Ingredients
Here’s the list of what we are going to use in this tutorial:
- Rails 3.2 - rubyonrails.org
- Devise - github.com/plataformatec/devise
- ActiveAdmin - activeadmin.info
- Heroku - heroku.com
- Android 4.1 (API 16) - developer.android.com
- UrlJsonAsyncTask - github.com/tonylukasavage/com.savagelook.android
- ActionBarSherlock - actionbarsherlock.com
The Rails Backend
Start by creating a new Rails app. At the moment I’m writing the latest version of rails is 3.2.8, check yours by using rails -v
in the command line.
Devise Setup
Add the Devise gem to your application:
Install the gems and create the default user model with the Devise generators.
Uncomment the following lines in the migration that are relative to the token_authenticatable
module:
Add the :token_authenticatable
to the devise modules in the user model:
Add the before filter :ensure_authentication_token
to the user model:
And finally uncomment the following line in the Devise initializer to enable the auth_token:
Bonus: add username to the user model
In our Android app we want to give possibility to the user to specify a username in the registration form. Let’s add this column to the table ‘users’ and the attribute to the attr_accesible
list in the user model.
Add the following line to the change
method in the migration.
Bonus: email confirmation from web, skip it from the Android app
The users of our Android app don’t want to wait to use it, so we skip the confirmation email check provided by Devise with the confirmable
module.
If you still want to use the module for the users that register from the webapp, just add this lines to the code.
Uncomment the following lines in the migration that are relative to the confirmable
module:
Add the :confirmable
to the devise available modules in the user model:
We need a way to bypass the confirmation step after the creation of a new user: setting a date to the confirmed_at
will do this. We add a new method to the user model that will be used in our Api controller.
We are done with the setup of our user model, we can now launch the rake tasks to create and migrate the database:
API Sessions Controller (login and logout)
Let’s start coding the sessions controller that will be used by our Android app to authenticate the users.
I want to use a namespace and a version for our API, so its controllers will be under the app/controller/api/v1/
folder.
The sessions controller has two actions: create for login and destroy for logout. The first accepts a user
JSON object as POST data with an email
and a password
parameters and returns an auth_token
if the user exists in the database and the password is correct. The logout action expects an auth_token
parameter in the url.
In the routes definition we add our namespace and the two login and logout routes.
Test the login
Let’s create a user to test the login with, open the rails console with rails console
in the command line and write:
Close the console and fire up the rails server
and in another command line use curl to invoke our new login API:
If everything went fine, you should see the last line saying this (the auth_token will be different):
Test the logout
Using the auth_token that the API gave us back when we logged in and specifying the DELETE
verb we can reset the authentication token of the user, logging him out.
The result will be a nice message informing us that we are logged out.
API Registrations Controller (register a new user)
The registrations controller extends the Devise one and has only one action, create. As you can see we skip the confirmation step with the method we added previously to the user model, we then save the new user and automatically log it in, returning the auth_token associated. Our user can then start using the API already logged in after the registration.
Add the register route to the API namespace:
Test the registration
Using the code we just added, we can now register new users from the JSON API. Try it out opening a command line and pasting this code.
If everything went fine, you should see the last line saying this (the id, dates and auth_token will be different):
ActiveAdmin administrative interface
Just to ease the following steps, I wanted to introduce a simple administrative interface to our web application: let’s add the ActiveAdmin gem (with dependencies) and with few lines of code we’ll have a full featured admin area.
Don’t forget to launch the bundle install
command.
ActiveAdmin will then generate the configuration file and some migrations. You can find more information in the official documentation: www.activeadmin.info
Add a new file to the app/admin
folder to configure the users admin interface:
Launch the rails server
and go to http://localhost:3000/admin and login with the default ActiveAdmin credentials:
- User: admin@example.com
- Password: password
Bonus: Deploy to Heroku
In the next steps we will be building an Android app from scratch that will consume our API. To better test it on our smartphones, we will need the web app reachable from the web, what better place than Heroku?
This tutorial won’t delve to much on the details of deploying a Rails app on the service, but you can read more on the official documentation: devcenter.heroku.com.
Download the Heroku toolbelt and create an account if you don’t have one.
Let’s start creating a Git repository and pushing it to Heroku. Take note of the app’s name that Heroku will create for you (something.herokuapp.com).
Now go to the address that Heroku created for your app and see if everything worked or not. More details on issues can be spotted with the heroku logs
command.
Part Two: The Android App
Proceed now to the second part of the tutorial, to learn how to build a fully featured Android App that can interact with the Ruby on Rails backend we just coded.
^Back to top