<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rutani Thakkar on Medium]]></title>
        <description><![CDATA[Stories by Rutani Thakkar on Medium]]></description>
        <link>https://medium.com/@rutani-thakkar?source=rss-cb91f99c90cf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9lTKi4_VvRD2DBq7TN-bCA.jpeg</url>
            <title>Stories by Rutani Thakkar on Medium</title>
            <link>https://medium.com/@rutani-thakkar?source=rss-cb91f99c90cf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 21:34:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rutani-thakkar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Implementing 2FA with Google Authenticator in Rails app]]></title>
            <link>https://medium.com/simform-engineering/implementing-2fa-with-google-authenticator-in-rails-app-db54332c995e?source=rss-cb91f99c90cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/db54332c995e</guid>
            <category><![CDATA[2fa-authentication]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[mfa]]></category>
            <category><![CDATA[google-authenticator]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Rutani Thakkar]]></dc:creator>
            <pubDate>Wed, 13 Sep 2023 11:17:39 GMT</pubDate>
            <atom:updated>2023-09-13T11:18:07.236Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Explore the 2FA concept with Google Authenticator in a Rails app.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nEoImZvQfnceCaIYa0oI7A.png" /></figure><p>Today, security is a top concern for both users and developers of web applications. Passwords alone often do not provide sufficient protection against account takeovers and fraudulent access. This is where two-factor authentication (2FA) comes in — adding an extra layer of identity verification for logins beyond just a username and password.</p><p>In this post, we’ll explore how to implement 2FA in a Ruby on Rails application using Google Authenticator, one of the most popular and user-friendly 2FA tools.</p><p><strong>What is 2FA?</strong></p><p><strong>2FA or two-factor authentication is when a system requires two steps to log a user in.</strong></p><p>2FA or MFA is mostly used in login screens to verify and double-check a user’s identity for additional security.</p><p>Rather than depending solely on a user’s email address and their password, 2FA attempts to decrease the risk of imposters acquiring access to personal data by properly establishing a user’s identity first. This is done by using an additional piece of information to verify the identity.</p><p>Because there are lots of ways to perform 2FA, there are also lots of different implementations. Some use email, others use SMS, etc. One of the implementations is Google Authenticator, which we’ll be using in our project.</p><h3>Let’s implement it</h3><p>Add the following line to your Gemfile and save it:</p><pre>gem &#39;google-authenticator-rails&#39;</pre><p>Go to terminal and run:</p><pre>bundle install</pre><h4>Add the required columns to your model.</h4><p>We need to add the columns used for storing the ‘google_secret’ and ‘mfa_secret’ to our User model.</p><p>The first column is <strong>google_secret</strong>. This is where we’ll store the encrypted code (which can be reset) used to connect the model (User) with Google Authenticator.</p><p>The second column is <strong>mfa_secret</strong>. This is where we’ll store a 6-digit code each time the user tries to log into their account. Every time the user logs out, the mfa_secret is reset to nil.</p><p>Create a migration for it:</p><pre>rails generate migration add_columns_to_users google_secret:string mfa_secret:integer</pre><p>In terminal, run the command:</p><pre>rails db:migrate</pre><h4>Connect Google authenticator with your model (User)</h4><p>To achieve this, you’ll add ‘acts_as_google_authenticated’ to your model (User).</p><p>‘encrypt_secrets: true.’ This setting will encrypt ‘google_secret’ inside of the database.</p><pre>Class User &lt; ApplicationRecord<br>  Acts_as_google_authenticated lookup_token: :mfa_secret, encrypt_secrets: true<br>end</pre><h4>Create a session object to be able to authenticate</h4><p>Now you need to create an empty model to store User data for authentication inside of it.</p><pre>  #app/models/user_mfa_session.rb<br>  class UserMfaSession &lt;  GoogleAuthenticatorRails::Session::Base<br>  end</pre><h4>Create the controller</h4><p>We’ll need to create a controller to check if the 6-digit code the user entered and stored into our ‘mfa_secret’ column is indeed correct. Depending on that, the controller will either save the correct session data into our session object(UserMfaSession) or alternatively prevent the user from accessing the resources they do not have access to until they’ve established their identity.</p><p>Our controller will have two methods, “<strong>new</strong>” and “<strong>create</strong>”.</p><p>The “new” method is the one that’ll load your view after you’ve finished authorization with your email (username) and password. Inside of this view, the user will need to input their 6 digit code which was created by Google Authenticator.</p><p>The “create” method is the actual backbone of it all and is where we’ll check if the code is valid. If it’s invalid, the view will redirect the user and prevent access until they verify their identity with a correct code. Here is the code we ended up with:</p><pre>class UserMfaSessionsController &lt; ApplicationController<br>  skip_before_action :check_mfa, only: [:new, :create]<br>  <br>  def new<br>  end<br><br>  def create<br>    user = current_user # grab your currently logged in user<br>    user.mfa_secret = params[:mfa_code]<br>    user.save!<br>    if user.google_authentic?(params[:mfa_code])<br>      UserMfaSession.create(user)<br>      redirect_to root_path<br>    else<br>      flash.now[:danger] = &quot;Invalid code&quot;<br>      render :new<br>    end<br>  end<br>end</pre><p>Let’s now move on to modifying our ApplicationController, our next step in integrating Google Authenticator.</p><pre># app/controllers/application_controller.rb<br>class ApplicationController &lt; ActionController::Base<br>  before_filter :check_mfa<br>  private<br>  def check_mfa<br>    if !(user_mfa_session = UserMfaSession.find) &amp;&amp; (user_mfa_session ? user_mfa_session.record == current_user : !user_mfa_session)<br>      redirect_to new_user_mfa_session_path<br>    end<br>    if &quot;/logout&quot; == request.path<br>      current_user.mfa_secret = nil<br>      current_user.save!<br>      UserMfaSession.destroy<br>    end<br>  end<br>end</pre><p>After the User fills in their correct credentials (email and password), they will be redirected to the view where they get asked to enter a 6-digit code from Google Authenticator.</p><p>Here is the relevant code:</p><pre>&lt;div class=&quot;mfa-container&quot;&gt;<br> &lt;%= form_tag user_mfa_session_path, method: :post, class: &quot;search-form&quot;, role: &quot;search&quot; do %&gt;<br>   &lt;div class=&quot;form-group&quot;&gt;<br>     &lt;%= label_tag &quot;Token&quot;, &#39;Google Authenticator code&#39;%&gt;<br>     &lt;%= text_field_tag &#39;mfa_code&#39;, params[:mfa_code], class: &quot;form-control form-control-line&quot; %&gt;<br>   &lt;/div&gt;<br>   &lt;%= submit_tag &#39;Log In&#39;, class: &quot;btn btn-block btn-lg btn-primary text-uppercase fs-12 fw-600&quot; %&gt;<br> &lt;% end %&gt;<br>&lt;/div&gt;</pre><p>we’ll be putting our view in the following place: app/views/user_mfa_sessions/new.html.erb</p><p>So, as you can see, when the User tries to log in, they get redirected by ApplicationController to “new_user_mfa_session_path“. This path leads to “user_mfa_session_controller“ and, more specifically, its method “new“.</p><p>After the User enters their code, they need to click on the “Log In“ button. On click, “:mfa_code“ containing the 6-digit code entered by the User gets sent through to the “create_user_mfa_session_path“ path, which ends up in the “create” method inside of our “user_mfa_session_controller“ file.</p><p>One more tip<strong> </strong>about “google_secret“. You need to send the “google_secret“ at least once to the User via email so only they can see it. You can do so either by sending a QR code or a key. The method for creating the QR code is “current_user.google_qr_uri“ and for the key, it is “current_user.google_secret_value“.</p><h4>Using Google Authenticator</h4><p>Now I’d like to show you how Google Authenticator actually works in practice.</p><pre>@user = User.new<br>@user.set_google_secret           # =&gt; true<br>@user.google_secret_value         # =&gt; 16-character plain-text secret, whatever the name of the secret column<br>@user.google_qr_uri               # =&gt; http://path.to.google/qr?with=params<br>@user.google_authentic?(123456)   # =&gt; true<br>@user.clear_google_secret!        # =&gt; true<br>@user.google_secret_value         # =&gt; nil</pre><p>The User must have a “google_secret“ value set in the database using &quot;user.set_google_secret”. The reason is that “google_secret“ contains the encrypted key connecting the User to their Google Authenticator. This key allows the User to connect their profile with the mobile Google Authenticator application. This code can be displayed either as a regular key or as a scannable QR code.</p><p>Now after our User has a “google_secret“ created inside the database, they need to connect their mobile application with their account so it can serve as a verification of identity in the future.</p><p>They can do so by either scanning the QR code (“current_user.google_qr_uri “) or by typing in the key manually (“current_user.google_secret_value“).</p><p>After our User connects their account to the mobile app, they should get to the view rendering their own 6-digit code. The below code is what the User enters on login:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*34HCU_txcIab8hkn" /><figcaption>Authentication code inside a authenticator app</figcaption></figure><p>Now our User is ready to use Google Secret. The procedure for authentication is now fairly straightforward:</p><ul><li>First, the User needs to do a standard authentication with their credentials (email/username and password).</li><li>Then the User will be redirected to the view with the 6-digit input field.</li><li>They’ll receive this in their Google Authenticator application.</li><li>Then they’ll enter the code in the input fields.</li><li>By clicking on “Log In,” they will now be able to make use of the rest of the site after passing Google Authenticator verification (or whatever resources you might have been hiding from them behind 2FA).</li></ul><h4>Conclusion</h4><p>2FA affords a better stage of protection than authentication techniques that rely on single-thing authentication. Rather than depending solely on a user’s email address and password, 2FA attempts to decrease the risk of imposters acquiring access to personal data by properly establishing a user’s identity first.</p><p>Thanks for tuning in, and we hope this was helpful for you!</p><blockquote><strong>For more updates on the latest tools and technologies, follow the </strong><a href="https://medium.com/simform-engineering"><strong>Simform Engineering</strong></a><strong> blog.</strong></blockquote><blockquote><strong>Follow Us: </strong><a href="https://twitter.com/simform"><strong>Twitter</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/simform/"><strong>LinkedIn</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db54332c995e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/simform-engineering/implementing-2fa-with-google-authenticator-in-rails-app-db54332c995e">Implementing 2FA with Google Authenticator in Rails app</a> was originally published in <a href="https://medium.com/simform-engineering">Simform Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>