This is a demo of using Devise and Authy together with the authy-devise
gem to add two factor authentication to a Rails application.
This demo was built with Ruby 2.5.1, but should run with any Ruby version that is supported by Rails/Devise.
To run this application download or clone it from GitHub, change into the directory and install the dependencies:
git clone https://github.com/twilio/authy-devise-demo.git
cd authy-devise-demo
bundle install
Create and migrate the database:
rails db:create db:migrate
Get your Authy application API key from the Twilio console and set it in your environment variables:
Through CLI:
export AUTHY_API_KEY=YOUR_API_KEY
Or in .env:
cp .env{.example,}
Place API key in .env file generated from above command.
Run the Rails application:
rails server
Visit localhost:3000 and sign up as a new user.
-
Create a new Rails application
rails new authy-devise-demo cd authy-devise-demo
-
Generate a controller
rails generate controller welcome index signed_in
-
Add a root path and signed in path to your
config/routes.rb
Rails.application.routes.draw do get "signed_in", to: "welcome#signed_in" root :to => 'welcome#index' end
-
Update the root and signed in views
# app/views/welcome/index.html.erb <h1>Welcome to the sample app</h1> <p><%= link_to "Sign up", new_user_registration_path %></p> <p><%= link_to "Sign in", new_user_session_path %></p>
# app/views/welcome/signed_in.html.erb <h1>Welcome to the sample app</h1> <p>You are signed in as <%= current_user.email %></p>
-
Add the
devise
anddevise-authy
gems to yourGemfile
and installgem 'devise', '~> 4.5' gem 'devise-authy', '~> 1.9'
bundle install
-
Install devise
rails generate devise:install
-
Add flash messages to the
app/views/layouts/application.html.erb
and update the default URL options inconfig/environments/development.rb
<p class="notice"><%= notice %></p> <p class="alert"><%= alert %></p>
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
-
Generate a user model with Devise and migrate the database
rails generate devise User rails db:migrate
-
Edit
app/controllers/welcome_controller.rb
and add:class WelcomeController < ApplicationController before_action :authenticate_user!, only: :signed_in def index redirect_to signed_in_path if user_signed_in? end def signed_in end end
-
Install
authy-devise
rails generate devise_authy:install
-
Open
config/initializers/authy.rb
and add your Authy API key (generate one in the Twilio Console)Authy.api_key = "YOUR_API_KEY" Authy.api_uri = "https://api.authy.com/"
-
Add
authy-devise
to theUser
model and run the resulting migrationrails generate devise_authy User rails db:migrate
-
Run the server and visit http://localhost:3000/users/sign_up to create a user
rails server
-
When signed in, visit http://localhost:3000/users/enable_authy to enable 2FA
-
Sign out and sign back in again and you will be required to enter your 2FA token