PHPackages                             srmklive/authy - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. srmklive/authy

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

srmklive/authy
==============

Plugin for enabling two-factor authentication in Laravel applications

v0.7.0(5y ago)6741.3k↓100%13MITPHP

Since Dec 4Pushed 3y ago4 watchersCompare

[ Source](https://github.com/srmklive/laravel-twofactor-authentication)[ Packagist](https://packagist.org/packages/srmklive/authy)[ Docs](https://github.com/srmklive/laravel-twofactor-authentication)[ RSS](/packages/srmklive-authy/feed)WikiDiscussions master Synced today

READMEChangelog (10)Dependencies (3)Versions (20)Used By (0)

Laravel Two-Factor Authentication
=================================

[](#laravel-two-factor-authentication)

[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Latest Version on Packagist](https://camo.githubusercontent.com/17397b5e4d3667324850d569de4e6deb06ceace47a700db262730c35f27412a9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73726d6b6c6976652f61757468792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/srmklive/authy)[![Total Downloads](https://camo.githubusercontent.com/8e9b7a668d737663e42a5177c059cb3650e719ae7f6414a598a43e6b9b02193d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73726d6b6c6976652f61757468792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/srmklive/authy)[![StyleCI](https://camo.githubusercontent.com/ad71d8f7bd562f652a55b3860b15b6e99cfba8b2018b625123ade1079f979778/68747470733a2f2f7374796c6563692e696f2f7265706f732f3437336175746879282939383033322f736869656c643f7374796c653d666c6174)](https://styleci.io/repos/47398032)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/f1b58b661d77746fc4e05ca87523c6bff11c5bed42d4a89fc146f41d9b56ff11/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f73726d6b6c6976652f6c61726176656c2d74776f666163746f722d61757468656e7469636174696f6e2f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/srmklive/laravel-twofactor-authentication/?branch=master)[![SensioLabsInsight](https://camo.githubusercontent.com/660cbecc8dc991ad51f0bbab327dc4e5a21bb7a3c2f7c1b07533c64e8fbfaeb2/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f31663165326162652d616566652d343439302d613031312d3065633866616336383630662f736d616c6c2e706e67)](https://insight.sensiolabs.com/projects/1f1e2abe-aefe-4490-a011-0ec8fac6860f)

- [Introduction](#introduction)
- [Installation](#installation)
- [Modify Login Workflow](#modify-login-workflow)
- [Usage](#usage)
- [Add a new TwoFactor Authentication Provider](#implement-new-provider)
- [Demo Application](#demo-application)

Introduction
------------

[](#introduction)

This plugins allows you to enable two-factor authentication in your Laravel applications.

**Only Laravel 5.1 or greater supported**

Installation
------------

[](#installation)

- Use following command to install:

```
composer require srmklive/authy
```

- Add the service provider to your $providers array in config/app.php file like:

```
Srmklive\Authy\Providers\AuthyServiceProvider::class
```

- Add the alias to your $aliases array in config/app.php file like:

```
'Authy' => Srmklive\Authy\Facades\Authy::class
```

- Run the following command to publish configuration:

```
php artisan vendor:publish --provider "Srmklive\Authy\Providers\AuthyServiceProvider"
```

- Run the following command to migrate user table changes to database:

```
php artisan migrate
```

- Add the following lines in your User model (e.g App\\User.php)

    - Before the class declaration, add these lines:

```
use Srmklive\Authy\Auth\TwoFactor\Authenticatable as TwoFactorAuthenticatable;
use Srmklive\Authy\Contracts\Auth\TwoFactor\Authenticatable as TwoFactorAuthenticatableContract;
```

- Now the change the class declaration. For example, if your class declaration is

```
class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
```

then change it to this:

```
class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract,
                                    TwoFactorAuthenticatableContract
```

- Now change the import traits line accordingly in user model file. For example if the line is:

```
use Authenticatable, Authorizable, CanResetPassword;
```

to

```
use Authenticatable, Authorizable, CanResetPassword, TwoFactorAuthenticatable;
```

- Lastly, add/update $hidden variable to hide 'two\_factor\_options' field from any DB call for user detail:

```
protected $hidden = [
	'two_factor_options'
];
```

Modifying Login Workflow
------------------------

[](#modifying-login-workflow)

- You need to add the following code to your `app\Http\Controllers\Auth\AuthController.php`.

```
    /**
     * Send the post-authentication response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @return \Illuminate\Http\Response
     */
    protected function authenticated(Request $request, Authenticatable $user)
    {
        if (Authy::getProvider()->isEnabled($user)) {
            return $this->logoutAndRedirectToTokenScreen($request, $user);
        }

        return redirect()->intended($this->redirectPath());
    }

    /**
     * Generate a redirect response to the two-factor token screen.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @return \Illuminate\Http\Response
     */
    protected function logoutAndRedirectToTokenScreen(Request $request, Authenticatable $user)
    {
        // Uncomment this line for Laravel 5.2+
        //auth($this->getGuard())->logout();

        // Uncomment this line for Laravel 5.1
        // auth()->logout();

        $request->session()->put('authy:auth:id', $user->id);

        return redirect(url('auth/token'));
    }

    /**
     * Show two-factor authentication page
     *
     * @return \Illuminate\Http\Response|\Illuminate\View\View
     */
    public function getToken()
    {
        return session('authy:auth:id') ? view('auth.token') : redirect(url('login'));
    }

    /**
     * Verify the two-factor authentication token.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postToken(Request $request)
    {
        $this->validate($request, ['token' => 'required']);
        if (! session('authy:auth:id')) {
            return redirect(url('login'));
        }

        // Uncomment these lines for use in Laravel 5.2+
        //$guard = config('auth.defaults.guard');
        //$provider = config('auth.guards.' . $guard . '.provider');
        //$model = config('auth.providers.' . $provider . '.model');

        // Uncomment the line below for use in Laravel 5.1
        // $model = config('auth.model');

        $user = (new $model)->findOrFail(
            $request->session()->pull('authy:auth:id')
        );

        if (Authy::getProvider()->tokenIsValid($user, $request->token)) {
            // Uncomment this line for Laravel 5.2+
            //auth($this->getGuard())->login($user);

            // Uncomment this line for Laravel 5.1
	        //auth()->login($user);

            return redirect()->intended($this->redirectPath());
        } else {
            return redirect(url('login'))->withErrors('Invalid two-factor authentication token provided!');
        }
    }
```

- Add route to verify two-factor authentication token

```
Route::get('auth/token','Auth\AuthController@getToken');
Route::post('auth/token','Auth\AuthController@postToken');
```

- Create view file in `resources/views/auth/token.blade.php`. Change this accordingly for your application. I have used code from [AdminLTE](https://github.com/almasaeed2010/AdminLTE) theme here.

```
@extends('layouts.app')

@section('content')

        Two-factor Authentication

        Validate your two-factor authentication token

            {!! csrf_field() !!}

            @if (count($errors) > 0)

                        @foreach ($errors->all() as $error)
                            {{ $error }}
                        @endforeach

            @endif

                    Verify Token

@endsection
```

Usage
-----

[](#usage)

- Registering User

```
$phone = '405-342-5699';
$code = 1;

$user = User::find(1);

$user->setAuthPhoneInformation(
    $code, $phone
);

try {
   Authy::getProvider()->register($user);

   $user->save();
} catch (Exception $e) {
   app(ExceptionHandler::class)->report($e);

   return response()->json(['error' => ['Unable To Register User']], 422);
}
```

- Send token via SMS

```
$user = User::find(1);

try {
   Authy::getProvider()->sendSmsToken($user);
} catch (Exception $e) {
   app(ExceptionHandler::class)->report($e);

   return response()->json(['error' => ['Unable To Send 2FA Login Token']], 422);
}
```

- Send token via phone call

```
$user = User::find(1);

try {
   Authy::getProvider()->sendPhoneCallToken($user);
} catch (Exception $e) {
   app(ExceptionHandler::class)->report($e);

   return response()->json(['error' => ['Unable To Send 2FA Login Token']], 422);
}
```

- Validating two-factor token

```
$user = User::find(1);

try {
   Authy::getProvider()->tokenIsValid($user, $token);
} catch (Exception $e) {
   app(ExceptionHandler::class)->report($e);

   return response()->json(['error' => ['Invalid 2FA Login Token Provided']], 422);
}
```

- Deleting User

```
$user = User::find(1);

try {
   Authy::getProvider()->delete($user);

   $user->save();
} catch (Exception $e) {
   app(ExceptionHandler::class)->report($e);

   return response()->json(['error' => ['Unable to Delete User']], 422);
}
```

Add a new TwoFactor Authentication Provider
-------------------------------------------

[](#add-a-new-twofactor-authentication-provider)

Currently this package uses two-factor authentication services from [**Authy**](https://www.authy.com). You can also implement another two-factor authentication provider by doing the following:

```
