Server-Sent Events (SSE) are real-time events sent from a server and received by a browser, perfect for updating the front end when a server receives a webhook. We’re going to look at how to use SSE to implement Authy OneTouch using Rails 4.

Our end result should look a bit like this:

Authy OneTouch

Two factor authentication usually means copying a bunch of numbers from your phone to the place you’re trying to log in. Authy OneTouch is a more user friendly version of two factor authentication. As you can see above, the user just needs to accept the authentication attempt and they are logged in.

On the back end Authy sends a webhook to the application with the result of the authentication request. The application can then log the user in and choose how it updates the front end. Check out our tutorial on how to get started with Authy OneTouch and Rails for more detail on how it all works.

Real-Time Rails 4?

You might be thinking that Rails 5 is finally bringing real-time action to the Ruby world with Action Cable. If you are then you probably missed that Rails 4 included ActionController::Live , a means of streaming data from a Rails in real-time. Connect this up to the EventSource API in browsers and we have a full implementation of Server-Sent Events that we can use to send data from the server to the browser in real-time.

The tutorial for Authy that I mentioned earlier actually implements the OneTouch flow by polling the server for updates. As polling can be inefficient and result in many unnecessary requests to our server let’s replace it with SSE.

Tools

To follow this post and implement SSE in Rails you’re going to need a few things:

Once you’ve got all that we’ll get the tutorial application set up.

Getting started

The best instructions for running the tutorial are available in the project README. Follow the instructions all the way through until the application is running locally, you have enabled OneTouch on your Authy application and set the webhook endpoint to your ngrok URL.

Once you’ve followed the instructions you should be able to visit your application at http://localhost:3000 and sign up as a new user. Logout and log back in again and you will be presented with the following two factor authentication flow.

You can see in the console that the JavaScript is constantly polling our backend to see if the user is authenticated yet.

Let’s replace that polling mechanism with Server-Sent Events.

Adding Server-Sent Events

In order to run real-time features like SSE (and Action Cable when Rails 5 is released) it is recommended to use a threaded server, like Puma. The project currently uses Unicorn so we need to update that.