Implementing Two-Factor Authentication in Laravel Applications

by bootsity on Jun 4, 2019 Parenting 940 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: 16317
Publishing
Articles: 77,218
Categories: 202
Online
Active Users: 1298
Members: 6
Guests: 1292
Bots: 12522
Visits last 24h (live): 5604
Visits last 24h (bots): 38892

Latest Comments

Spending time with Patparganj Escorts Service felt more like a premium romantic date than a normal meetup. She was elegant, flirtatious, and knew exactly how to keep the mood warm and...
Step into the arena of pursuing your every wicked fantasy through our Escorts in Burari , established to satisfy every Sexual Need and Want.  
유쾌한 게시물,이 매혹적인 작업을 계속 인식하십시오. 이 주제가이 사이트에서 마찬가지로 확보되고 있다는 것을 진심으로 알고 있으므로 이에 대해 이야기 할 시간을 마련 해주셔서 감사합니다! 미투벳 평생도메인  
sabse fast result yaha aata h  <a href="https://mysattakings.com/">Satta king</a> <a href="https://mysattakings.com/">Sattaking</a> <a...
sabse fast result yaha aata h  <a href="https://mysattakings.com/">Satta king</a> <a href="https://mysattakings.com/">Sattaking</a> <a...
유익한 웹 사이트를 게시하는 데 아주 좋습니다. 웹 로그는 유용 할뿐만 아니라 창의적이기도합니다. 레드벨벳카지노
Thanks for providing recent updates regarding the concern, I look forward to read more. zxx 도메인 주소    
I think the part about documenting everything is so key. It's tempting to just rush ahead with the exciting parts, but seriously, keeping a detailed journal could save you a ton of headaches down...
on May 9, 2026 about How to Start an Invention Idea
나는 이것이 유익한 게시물이라고 생각하며 매우 유용하고 지식이 풍부합니다. 따라서이 기사를 작성하는 데 많은 노력을 기울여 주셔서 감사합니다  유투벳 평생도메인      
Our agency proudly offers premium companionship arrangements created for clients seeking comfort and reliable coordination. With professional support and organized booking assistance, choosing...
on May 7, 2026 about NBC Sports Gold Activate

Translate To: