In this tutorial you can learn how to implement two-factor authentication in Laravel. You can follow the the steps listed here.
What is two-factor authentication?
Two-factor authentication is a mechanism to provide additional security to your login system. In addition to username and password you have to provide the token which will be sent to your phone as a SMS.
You can use the Auty for two-factor authentication but here we will do it from scratch
To start this tutorial you can install fresh Laravel project in your web server. If you new to Laravel you can read this tutorial. This has the steps for installation
We need to add phone
field to the registration form. So you can open the
resources\views\auth\register.blade.php
and add the following code. This should be placed just below the E-mail field
Now you can see the Phone field in registration form. You can enter the phone number to receive token via SMS
We need to add some fields to database for two factor authentication implementation
I am going to add phone
field to hold the phone number, code
field to store the token sent to the mobile device and isverified
field for storing the status of the verification
I am going to use following artisan command to create database migration file
php artisan make:migration add_extra_field_to_users_table
This will create migration file at database\migrations
folder. Now lets add code to add fields
public function up() { Schema::table('users', function(Blueprint $table) { $table->string('phone'); $table->string('code'); $table->integer('isverified'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function(Blueprint $table) { $table->dropColumn('phone'); $table->dropColumn('code'); $table->dropColumn('isverified'); }); }
We can use random key generator to generate token
composer require gladcodes/keygen
You have generate the token inside the create
method of RegisterController
in App\Http\Controllers\Auth
$key = Keygen::numeric(4)->generate();
Once you generate the token you have to send it to phone and store it in the users
table. You can use Nexmo API to send SMS
You can install the php client library
composer require nexmo/laravel
You can add Nexmo\Laravel\NexmoServiceProvider
to the providers array in your config/app.php
'providers' => [ // other code Nexmo\Laravel\NexmoServiceProvider::class, ],
You can put the key and secret in your .env
file.
NEXMO_KEY=c2f2ecaa NEXMO_SECRET=23324de3c4b9a7b6
Now you can add following code inside the create method to send token via SMS
protected function create(array $data) { // send sms code $key = Keygen::numeric(4)->generate(); Nexmo::message()->send([ 'to' => $data['phone'], 'from' => '16105552344', 'text' => 'Your verifcation code : '.$key ]); return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'phone' => $data['phone'], 'code' => $key, 'password' => bcrypt($data['password']), ]); }
This will send the SMS and phone number and token will be stored in users
table in database
Upto this point you have generated the token and send to mobile device when user regitser in the application first time.
Now when user tries to open the login page he should be prompted to enter the token and it should be validated with entry in the users
table
I will create a middleware to check whether user has verified his phone number with token
To create the middlewre run the following command at your terminal
php artisan make:middleware PhoneVerification
You can add the following code to App\Http\Middleware\PhoneVerification.php
file
user(); if (($user!=null) && ($user->isverified == 0)){ return redirect('verify'); } return $next($request); } }
Next I am going to assign this middleware as a route middleware. You can add the following code to Kernal.php
file in App\Http
protected $routeMiddleware = [ //other code 'auth' => \App\Http\Middleware\PhoneVerification::class, ];
In this, you can create controller to view the form to enter the token. First we will create the controller and then we will create the view
php artisan make:controller PhoneVerifyController
Now you can add the following two actions to the controller
public function verify(){ return view('verify'); } public function verifySubmit(Request $request){ $user = Auth::user(); if($user->code==$request->code){ $user->isverified=1; $user->save(); } return redirect("/home"); }
You can see two action in this code. Action verify()
will show you the form and action verifySubmit()
will verify the user submitted value
Your routes\web.php
file shouls have following entry
Route::get('/verify', 'PhoneVerifyController@verify'); Route::post('/verify', 'PhoneVerifyController@verifySubmit')->name('verify.submit');
Finally resources\views\verify.blade.php
will have following code to display the form
@extends('layouts.app') @section('content')
@endsection
You will see the following screen after you login to the system
If you want to know more about Laravel please see out tutorials