PHPackages                             triopsi/simple-two-factor - 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. triopsi/simple-two-factor

ActiveCakephp-plugin[Authentication &amp; Authorization](/categories/authentication)

triopsi/simple-two-factor
=========================

A simple two factor auth middleware for CakePHP

v1.0.6(1y ago)163MITPHPPHP &gt;=8.2CI passing

Since Feb 21Pushed 1y ago2 watchersCompare

[ Source](https://github.com/triopsi/SimpleTwoFactor)[ Packagist](https://packagist.org/packages/triopsi/simple-two-factor)[ RSS](/packages/triopsi-simple-two-factor/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (7)Dependencies (7)Versions (9)Used By (0)

[![Licensed under the MIT License](https://camo.githubusercontent.com/08cef40a9105b6526ca22088bc514fbfdbc9aac1ddbf8d4e6c750e3a88a44dca/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d626c75652e737667)](https://opensource.org/license/mit)[![Requires PHP 8.2.0](https://camo.githubusercontent.com/cfcd5b535d0f4540e9311bb1c8bf03bf9e842e6702497b2f49589f1f3274eaa2/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e322e302d626c75652e737667)](https://php.net)[![Last Commit](https://camo.githubusercontent.com/122777d53851e4d6146ee190660718e333945a446605fd4323a467c43d326d8f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f7472696f7073692f53696d706c6554776f466163746f722e737667)](https://github.com/triopsi/SimpleTwoFactor/commits/master)[![codecov](https://camo.githubusercontent.com/9737cdad68d3e82e4bde15c3e7a4ef7334164f5ab343eb2225cdfdf3ed58ea48/68747470733a2f2f636f6465636f762e696f2f6769746875622f7472696f7073692f53696d706c6554776f466163746f722f67726170682f62616467652e7376673f746f6b656e3d3830324f313534345742)](https://codecov.io/github/triopsi/SimpleTwoFactor)

SimpleTwoFactor Plugin for CakePHP 4
====================================

[](#simpletwofactor-plugin-for-cakephp-4)

This plugin provides a simple two-factor authentication (2FA) mechanism for CakePHP 4 applications. It uses the [RobThree/TwoFactorAuth](https://github.com/RobThree/TwoFactorAuth) library to handle the generation and verification of 2FA codes.

- [SimpleTwoFactor Plugin for CakePHP 4](#simpletwofactor-plugin-for-cakephp-4)
    - [Features](#features)
    - [Requirements](#requirements)
    - [Two-Factor Authentication (2FA) Workflow](#two-factor-authentication-2fa-workflow)
    - [Workflow Overview](#workflow-overview)
    - [Technical Details](#technical-details)
    - [Installation](#installation)
    - [Configuration](#configuration)
        - [1. User Secret Store](#1-user-secret-store)
        - [2. Load the Plugin](#2-load-the-plugin)
        - [3. Add Middleware](#3-add-middleware)
            - [Middleware Options](#middleware-options)
            - [Example Configuration in Application.php](#example-configuration-in-applicationphp)
            - [4. Example Controller Action](#4-example-controller-action)
            - [5. Example View](#5-example-view)
    - [SimpleTwoFactorComponent for CakePHP 4](#simpletwofactorcomponent-for-cakephp-4)
        - [Features](#features-1)
        - [Load the Component](#load-the-component)
        - [Generating a QR Code](#generating-a-qr-code)
        - [Example View](#example-view)
        - [Logout](#logout)
    - [Bugs &amp; Feedback](#bugs--feedback)
    - [License](#license)

Features
--------

[](#features)

- ***Easy Integration:*** Seamlessly integrates with CakePHP 4's authentication system.
- ***Configurable:*** Provides multiple configuration options to customize the 2FA process.
- ***Middleware Support:*** Includes middleware to enforce 2FA on specific routes.
- ***QR Code Generation:*** Supports QR code generation for easy setup with 2FA apps.
- ***Customizable Views:*** Allows customization of the 2FA verification form.
- ***Session Management:*** Manages 2FA verification status using session keys.
- ***Multiple Algorithms:*** Supports various algorithms for generating 2FA codes (SHA1, SHA256, SHA512, MD5).
- ***Flexible Providers:*** Supports different QR code and random number generator providers.
- ***Security:*** Enhances security by adding an additional layer of authentication.

Requirements
------------

[](#requirements)

- CakePHP 4.\*
- PHP 8.2

Two-Factor Authentication (2FA) Workflow
----------------------------------------

[](#two-factor-authentication-2fa-workflow)

Two-Factor Authentication adds an additional layer of security to the authentication process by requiring not only a username and password but also a unique code generated by an authentication app.

Workflow Overview
-----------------

[](#workflow-overview)

1. **User Registration with 2FA Setup**

    - After registering or editing their profile, the user is presented with a QR code.
    - The QR code contains a secret key.
    - The user scans the QR code using an authentication app (e.g., Google Authenticator, Authy).
    - This generates a secret pair shared between the server and the user’s device.
2. **Subsequent Logins**

    - After entering the correct username and password, the user is prompted for a Two-Factor Authentication (2FA) code.
    - The user opens the authentication app to retrieve the current TOTP (Time-based One-Time Password).
    - The TOTP code is submitted to the server.
3. **Verification and Access**

    - The server verifies the TOTP code using the shared secret.
    - If the code is correct and matches the expected value, the user is granted access to the application.
    - If the code is incorrect, access is denied.

Technical Details
-----------------

[](#technical-details)

- **QR Code Generation:** The server generates a QR code containing the secret.
- **Secret Storage:** The secret is securely stored in the user database.
- **TOTP Code Verification:** At each login, the server uses the stored secret to verify the TOTP code submitted by the user.

This process ensures that even if a user's primary credentials are compromised, unauthorized access is prevented without the second factor of authentication.

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

[](#installation)

You can install this plugin into your CakePHP application using composer.

The recommended way to install composer packages is:

```
composer require triopsi/simple-two-factor
```

Configuration
-------------

[](#configuration)

### 1. User Secret Store

[](#1-user-secret-store)

To save the secret and to assign the user. The plugin requires a secret field in the user table. This could look as follows:

```
ALTER TABLE `users` ADD `secret` VARCHAR(255) NULL;
```

or via migration:

```
bin/cake bake migration AddSecretToUsers secret:string[255]:null
```

### 2. Load the Plugin

[](#2-load-the-plugin)

Load the plugin in your `Application.php` file:

```
public function bootstrap(): void {
    parent::bootstrap();
    $this->addPlugin('SimpleTwoFactor');
}
```

Alternatively, execute the following line:

```
bin/cake plugin load SimpleTwoFactor
```

### 3. Add Middleware

[](#3-add-middleware)

Add the TwoFactorMiddleware to your middleware queue in `src/Application.php`. Make sure to add it directly under the AuthenticationMiddleware.

```
use SimpleTwoFactor\Middleware\TwoFactorMiddleware;

public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue {
    $middlewareQueue
        ->add(new ErrorHandlerMiddleware(Configure::read('Error')))
        ->add(new AssetMiddleware())
        ->add(new RoutingMiddleware($this))
        ->add(new BodyParserMiddleware())
        ->add(new AuthenticationMiddleware($this))
        ->add(new TwoFactorMiddleware()); // Add TwoFactorMiddleware here

    return $middlewareQueue;
}
```

#### Middleware Options

[](#middleware-options)

The TwoFactorMiddleware class provides several configuration options that can be customized to fit your application's needs. Below are the available options along with their explanations:

- ***userSessionKey:*** The session key to store the user in. Default is 'Auth'.
- ***codeField:*** The field name in the request that contains the 2FA code. Default is 'code'.
- ***redirectUrl:*** The URL to redirect unauthenticated users to. Default is '/users/verifytfa'.
- ***sessionKeyVerified:*** The session key to store the 2FA verified status. Default is '2fa\_verified'.
- ***userKeySecret:*** The user key to store the 2FA secret. Default is '\_2tfa'.
- ***isEnabled2faProperty:*** The user key to check if 2FA is enabled. Default is 'secret\_2tfa'.
- ***urlChecker:*** The URL checker config. Default is 'Authentication.Default'.
- ***issuer:*** The issuer name displayed in the 2FA app. Default is null.
- ***digits:*** The number of digits in the 2FA code. Default is 6.
- ***period:*** The number of seconds a 2FA code is valid. Default is 30.
- ***algorithm:*** The algorithm used for generating the 2FA code. Options are 'sha1', 'sha256', 'sha512', 'md5'. Default is 'sha1'.
- ***qrcodeprovider:*** The QR code provider. Options are 'BaconQrCodeProvider', 'EndroidQrCodeProvider'. Default is 'BaconQrCodeProvider'.
- ***rngprovider:*** The random number generator provider. Default is null.
- ***timeprovider:*** The time provider. Default is null.

#### Example Configuration in Application.php

[](#example-configuration-in-applicationphp)

To configure the TwoFactorMiddleware in your CakePHP application, you need to set the options in the middleware method of your `Application.php` file.

```
use SimpleTwoFactor\Middleware\TwoFactorMiddleware;

public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue {
    $middlewareQueue
        ->add(new ErrorHandlerMiddleware(Configure::read('Error')))
        ->add(new AssetMiddleware())
        ->add(new RoutingMiddleware($this))
        ->add(new BodyParserMiddleware())
        ->add(new AuthenticationMiddleware($this))
        ->add(new TwoFactorMiddleware([
            'redirectUrl' => '/users/verifytfa',
            'userKeySecret' => 'secret_2tfa',
            'isEnabled2faProperty' => 'secret_2tfa',
            'issuer' => 'MyApp',
            'digits' => 6,
            'period' => 30,
            'algorithm' => 'sha1',
            'qrcodeprovider' => 'BaconQrCodeProvider'
        ]));

    return $middlewareQueue;
}
```

> ! It is important that the TwoFactorMiddleware is placed after the AuthenticationMiddleware. If the order is incorrect, the plugin cannot work properly.

#### 4. Example Controller Action

[](#4-example-controller-action)

Create a method in your UsersController to handle the 2FA verification.

*Example for UsersController.php*

```
namespace App\Controller;

use App\Controller\AppController;
use SimpleTwoFactor\Result\Result;

class UsersController extends AppController
{
    public function initialize(): void {
        parent::initialize();
        $this->loadComponent('SimpleTwoFactor.SimpleTwoFactor');
    }

    public function verifytfa() {
        $result = $this->SimpleTwoFactor->getResult();
        if ($result->getStatus() == Result::SIMPLE_TWO_FA_AUTH_FAILED) {
            $this->Flash->error('Invalid 2FA code');
        } elseif ($result->getStatus() == Result::SIMPLE_TWO_FA_AUTH_SUCCESS) {
            $this->Flash->success('Welcome back!');
            return $this->redirect($this->Auth->redirectUrl());
        }
    }
}
```

#### 5. Example View

[](#5-example-view)

Create a view for the 2FA verification form.

*Example for verifytfa.php*

```
