Implementing Two-Factor Authentication in Laravel Applications

by bootsity on Jun 4, 2019 Parenting 968 Views

1. Introduction

Two-factor Authentication, also known as 2FA is a type, or subset, of Multi-factor Authentication. Multi-factor authentication is a method of confirming identity using by combination of two or more claimed identities. 2FA is a method of confirming users’ claimed identities by using a combination any two different factors from below:

  • something they know
  • something they have
  • something they are

Essentially, this approach allows us to create a restriction for certain areas in our application. It ensures that only the right people have access to the resources in those areas. In this article we are going to take a look at how we can implement 2FA in our Laravel application in really simple steps. Also, we will be using email as our means of verification of user’s identity. Let us dive right in.

2. Setup for Two Factor Authentication

We need the following to get started:

3. The Process or Workflow

When an user tries to access a route protected by 2FA, he gets a mail notification containing an OTP code and is redirected to a form where they can input the OTP.

When this OTP is entered and is verified to be correct, they are able to access the resource, if the code is incorrect, they are not granted access.

The user session will last for the same time as Laravel’s set session lifetime. The duration for this can be found and modified in /config/sessions.php

4. Adding Two-factor Form

We are going to add a form which allows users to enter the OTP that was received in their email addresses and submit it for processing by the application’s backend. The markup for the form can be found here. The excerpt from from code is:

  1. <form action="" method="post">
  2. @csrf
  3. <div class="form-group">
  4. <label for="token">Token</label>
  5. <input type="text" name="token" placeholder="Enter OTP" class="form-control{{ $errors->has('token') ? ' is-invalid' : '' }}" id="token">
  6. @if($errors->has('token'))
  7. <span class="invalid-feedback" role="alert">
  8. <strong>{{ $errors->first('token') }}</strong>
  9. </span>
  10. @endif
  11. </div>
  12. <button class="btn btn-primary btn-large">Verify</button>
  13. </form>

5. Writing Database Migration

We have to ensure that our users’ migration contains an email field. As we are using email as of of the factor in 2FA in this article. Users migration are generally present in file  /database/migrations/<datetime>_create_users_migration.php

We need two extra fields in the users migration: two_factor_token and two_factor_expiry. We can do this by generating a new migration with this command:

  • php artisan make:migration add_2fa_fields_to_users_table --table=users

The command above will generate the migration and set the table as users, so we can add the following within the migration’s schema closure:

  1. // this goes in the up() method
  2. $table->string('two_factor_token')->nullable();
  3. $table->datetime('two_factor_expiry')->nullable();
  4.  
  5. // this goes in the down() method
  6. $table->dropColumn('two_factor_expiry');
  7. $table->dropColumn('two_factor_token');

After saving this file, we will run the command: php artisan migrate to append the fields to the users table.

6. Generating Middleware and Mailables

We are adding a middleware which will serve as a filter for requests coming into the route we protect with 2FA.

To generate the middleware, run:

  • php artisan make:middleware TwoFactorVerification

In the handle method of this middleware, we are going to check if the current time is greater than the time in the two_factor_expiry field of the users’ migration.

The request will pass if the condition specified evaluates to true, otherwise, a OTP is generated and sent to their mail, they are redirected to the form to input the token they got via email.

Our middleware looks like:

  1. $user = auth()->user();
  2.  
  3. if ($user->two_factor_expiry > \Carbon\Carbon::now()) {
  4. return $next($request);
  5. }
  6.  
  7. $user->two_factor_token = str_random(10);
  8. $user->save();
  9.  
  10. \Mail::to($user)->send(new TwoFactorAuthMail($user->two_factor_token));
  11.  
  12. return redirect('/2fa');

Now, we need to generate a mailable (TwoFactorAuthMail) to configure the mail to be sent to the user.

Also, do not forget to import the necessary namespaces and classes.

We can quickly generate the mailable with this command: php artisan make:mail TwoFactorAuthMail

Pass in a $token argument (or variable) to the mailable’s constructor such that in the end, the mailable looks like this:

  1. public $token;
  2.  
  3. public function __construct($token)
  4. {
  5. $this->token = $token;
  6. }
  7.  
  8. public function build()
  9. {
  10. returnhttps://article-realm.com/article/Home-Family/Parenting/2510-Implementing-Two-Factor-Authentication-in-Laravel-Applications.html

URL

https://bootsity.com/laravel/implementing-two-factor-authentication-in-laravel-applications
In this article we are going to take a look at how we can implement 2FA in our Laravel application in really simple steps

Comments

No comments have been left here yet. Be the first who will do it.
Safety

captchaPlease input letters you see on the image.
Click on image to redraw.

Reviews

Guest

Overall Rating:

Statistics

Members
Members: 16795
Publishing
Articles: 78,668
Categories: 202
Online
Active Users: 531
Members: 0
Guests: 531
Bots: 2721
Visits last 24h (live): 18536
Visits last 24h (bots): 39520

Latest Comments

While researching academic search trends, I realized that the phrases students use often differ from what keyword tools suggest. Browsing forums and discussion boards revealed that many users...
It is always great to see travel companies making trips more affordable and convenient for people who love exploring new places. Finding reliable packages for flights, hotels, and tours can make...
on Aug 5, 2026 about Travel Case
It’s difficult to find well-informed people in this particular subject, however, unblocked games you seem like you know what you’re talking about! Thank   
on Aug 5, 2026 about Can WiFi Extender cause Problems
Your means of describing the whole thing in this paragraph is actually good, all be able to without difficulty understand it, Thanks a lot.  
[url=https://lsm999dna.online/login/]ล็อกอิน lsm99[/url] I am really inspired with your writing skills and also with the structure on your weblog. Is this a paid topic or did you modify it your...
https://lsm999dna.online/ I was suggested this web site by my cousin. I am not sure whether this  post is written by him as nobody else know such detailed about my problem. You’re wonderful!...
Trying to get around the busy capital is a lot more enjoyable once you rely on a premier Escort Service in Delhi , it brings clients unmatched professionalism, discreet arrangements, charming...
Looking for reliable company in the capital? Try Delhi Escorts for a discreet and professional experience. The service is well-managed, private, and focused on comfort. Guests appreciate the...
"APKPure makes it easy to discover the latest business and productivity apps. It's a useful platform for anyone looking to grow or manage an online business with the right tools."
on Aug 4, 2026 about The Latest Online Business
Your wave continually advances. The levels  space waves may initially appear to be manageable; however, the difficulty rapidly escalates as narrower corridors, unanticipated turns, moving...

Translate To: