Implementing Two-Factor Authentication in Laravel Applications

by bootsity on Jun 4, 2019 Parenting 949 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: 16485
Publishing
Articles: 77,749
Categories: 202
Online
Active Users: 908
Members: 2
Guests: 906
Bots: 16291
Visits last 24h (live): 2482
Visits last 24h (bots): 47016

Latest Comments

You completed certain reliable points there. I did a search on the subject and found nearly all persons will agree with your blog.  amindhk.com
It is my first visit to your blog, and I am very impressed with the articles that you serve. Give adequate knowledge for me. Thank you for sharing useful material. I will be back for the more...
Do you think the demand was something you expected from the beginning, or did it grow more organically over time?   https://alfcasinoonline.com
on Jun 10, 2026 about PowerHitter
Good composed article. It will be steady to any individual who uses it, including me. Continue doing what you are doing – can'r hold up to peruse more posts.  mjx hyper go
I'm really enjoying the design and layout of your site. It's a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a developer to...
Strike Login refers to the authentication process that allows registered users to securely access their Strike accounts. The login system verifies user credentials and grants authorized access to...
The MetaMask Wallet Extension is a browser-based cryptocurrency wallet that allows users to store, send, receive, and manage digital assets directly from their web browser. visit here:-...
Bitget Login refers to the authentication process that allows registered users to access their Bitget accounts through the platform's website or mobile application. visit here:- Bitget Login
 The Canadian crypto market is evolving rapidly, and platforms like Netcoins continue attracting users looking for a simpler way to trade digital currencies. Visit here:- Netcoins Login
솔직히 말해서 스타일로 글을 쓰고 좋은 칭찬을받는 것은 꽤 어렵지만, 너무 차분하고 시원한 느낌으로 해냈고 당신은 일을 잘했습니다. 이 기사는 스타일이 돋보이며 좋은 칭찬을하고 있습니다. 베스트!  럭키 도메인 주소    

Translate To: