Implementing Two-Factor Authentication in Laravel Applications

by bootsity on Jun 4, 2019 Parenting 957 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: 16691
Publishing
Articles: 78,294
Categories: 202
Online
Active Users: 721
Members: 11
Guests: 710
Bots: 17509
Visits last 24h (live): 1788
Visits last 24h (bots): 44923

Latest Comments

Great article! It's fascinating to learn about the rich history and unique experience of the Darjeeling Himalayan Railway. Well-written and informative. As a pitch deck design agency , we...
This content effectively details welfare programs in Andhra Pradesh. Chandrababu Naidu's initiatives are clearly outlined, demonstrating a focus on community and transparency. Just like a player...
That's a really insightful post about picking the right web design company! It truly highlights how crucial it is to align the design with your business model. I especially resonate with the point...
I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog, I will keep visiting...
I genuinely like you're making style, inconceivable information, thankyou for posting 텐바이텐  
You have a good point here!I totally agree with what you have said!!Thanks for sharing your views...hope more people will read this article!!  트랜드 도메인 주소    
Logging into your Chime account is a quick and secure process designed for instant financial access. To begin, visit the official Chime website or open the mobile app on your device. Navigate to...
on Jul 13, 2026 about Blogging
This is my first time visit to your blog and I am very interested in the articles that you serve. Provide enough knowledge for me. Thank you for sharing useful and don't forget, keep sharing...
This is my first time visit to your blog and I am very interested in the articles that you serve. Provide enough knowledge for me. Thank you for sharing useful and don't forget, keep sharing...
The sophisticated online platform for Escorts Gurgaon features intuitive filtering options that allow potential clients to narrow their search based on specific preferences and availability.  

Translate To: