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:
- Fresh Laravel project
- Laravel’s default authentication views and logic (this is generated by running php artisan make:auth in a fresh Laravel application)
- Mail server for test purposes (Mailtrap)
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:
- <form action="" method="post">
- @csrf
- <div class="form-group">
- <label for="token">Token</label>
- <input type="text" name="token" placeholder="Enter OTP" class="form-control{{ $errors->has('token') ? ' is-invalid' : '' }}" id="token">
- @if($errors->has('token'))
- <span class="invalid-feedback" role="alert">
- <strong>{{ $errors->first('token') }}</strong>
- </span>
- @endif
- </div>
- <button class="btn btn-primary btn-large">Verify</button>
- </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:
- // this goes in the up() method
- $table->string('two_factor_token')->nullable();
- $table->datetime('two_factor_expiry')->nullable();
- // this goes in the down() method
- $table->dropColumn('two_factor_expiry');
- $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:
- $user = auth()->user();
- if ($user->two_factor_expiry > \Carbon\Carbon::now()) {
- return $next($request);
- }
- $user->two_factor_token = str_random(10);
- $user->save();
- \Mail::to($user)->send(new TwoFactorAuthMail($user->two_factor_token));
- 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:
- public $token;
- public function __construct($token)
- {
- $this->token = $token;
- }
- public function build()
- {
- 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-applicationsIn this article we are going to take a look at how we can implement 2FA in our Laravel application in really simple steps
Reviews
Comments
Most Recent Articles
- Feb 22, 2021 Free practice Test on Entrance Exam,Selective High Schools Test - VIC,Australia by I learn education
- Feb 10, 2018 Tempests and Slaughter’ ebook overview: fitting Numair Salmalín by Olivia Sorbet
Most Viewed Articles
- 1069 hits Tempests and Slaughter’ ebook overview: fitting Numair Salmalín by Olivia Sorbet
- 365 hits Free practice Test on Entrance Exam,Selective High Schools Test - VIC,Australia by I learn education
Popular Articles
In today’s competitive world, one must be knowledgeable about the latest online business that works effectively through seo services....
77367 Views
Are you caught in between seo companies introduced by a friend, researched by you, or advertised by a particular site? If that is the...
32686 Views
Walmart is being sued by a customer alleging racial discrimination. The customer who has filed a lawsuit against the retailer claims that it...
13708 Views
If you have an idea for a new product, you can start by performing a patent search. This will help you decide whether your idea could become the...
11085 Views
Statistics
Members | |
---|---|
Members: | 15316 |
Publishing | |
---|---|
Articles: | 63,054 |
Categories: | 202 |
Online | |
---|---|
Active Users: | 40 |
Members: | 0 |
Guests: | 40 |
Bots: | 1142 |
Visits last 24h (live): | 1846 |
Visits last 24h (bots): | 25710 |