Implementing Two-Factor Authentication in Laravel Applications

by bootsity on Jun 4, 2019 Parenting 985 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: 17030
Publishing
Articles: 79,436
Categories: 202
Online
Active Users: 2143
Members: 10
Guests: 2133
Bots: 28952
Visits last 24h (live): 4154
Visits last 24h (bots): 63704

Latest Comments

Meera offers premium Aligarh call girl service with elegance and sophistication. Her stylish personality, engaging conversations, and positive attitude make every meeting enjoyable. She...
on Sep 16, 2026 about sonammathuri
Bài viết chia sẻ chi tiết về các chương trình phúc lợi của Chandrababu Naidu hay quá! Vừa tìm hiểu xong thông tin giải trí lướt vài chương truyện tại ưng tỷ comics  thì đúng chuẩn bài thư giãn....
Shikhsa provides quality Kolkata call girl service and social services focused on friendly interaction, conversation, and enjoyable experiences.     
on Sep 16, 2026 about sonammathuri
나는 당신이 이것에 배치 한 각각의 공연을 즐깁니다. 정말 유용한 곳이 될 거라고 확신합니다. 나는 또한 기뻤다. 잘 했어!  레고벳      
아주 잘 쓰여진 이야기. 저뿐만 아니라 그것을 활용하는 모든 사람에게 유용 할 것입니다. 좋은 일을 계속하십시오 – 나는 확실히 더 많은 포스트를 읽을 것입니다  올라프벳    
당신은 함께 논쟁하기가 실질적으로 어렵다는 것을 너무 많이 이해합니다 (실제로 내가 원하는 것은 아닙니다 ... 하하). 당신은 확실히 수십 년 동안 논의 된 주제로 최신 스핀을 넣었습니다. 멋진 물건, 그냥 멋져요!  마리오벳  
Starting an invention is exciting, but it requires careful planning just like building a winning strategy in sports. I once had a product idea and realized the importance of thorough research...
on Sep 16, 2026 about How to Start an Invention Idea
"이것은 훌륭한 기사입니다. 많은 정보를 감안할 때 이러한 유형의 기사는 사용자의 웹 사이트에 대한 관심을 유지하고 계속해서 더 많은 정보를 공유합니다. 행운을 빕니다.  레고벳      
나는 그들이 매우 도움이 될 것이라고 확신하기 때문에 사람들을 귀하의 사이트로 다시 보내기 위해 귀하의 사이트를 내 소셜 미디어 계정에 추가하고 공유했습니다.  올라프벳  
"이것은 훌륭한 기사입니다. 많은 정보를 감안할 때 이러한 유형의 기사는 사용자의 웹 사이트에 대한 관심을 유지하고 계속해서 더 많은 정보를 공유합니다. 행운을 빕니다.  마리오벳  

Translate To: