PHP library for Two Factor Authentication (TFA / 2FA)

Overview

Logo PHP library for Two Factor Authentication

Build status Latest Stable Version License Downloads Code Climate PayPal donate button

PHP library for two-factor (or multi-factor) authentication using TOTP and QR-codes. Inspired by, based on but most importantly an improvement on 'PHPGangsta/GoogleAuthenticator'. There's a .Net implementation of this library as well.

Requirements

  • Tested on PHP 5.6 up to 8.0
  • cURL when using the provided QRServerProvider (default), ImageChartsQRCodeProvider or QRicketProvider but you can also provide your own QR-code provider.
  • random_bytes(), MCrypt, OpenSSL or Hash depending on which built-in RNG you use (TwoFactorAuth will try to 'autodetect' and use the best available); however: feel free to provide your own (CS)RNG.

Optionally, you may need:

Installation

The best way of installing this library is with composer:

php composer.phar require robthree/twofactorauth

Usage

For a quick start, have a look at the getting started page or try out the demo.

If you need more in-depth information about the configuration available then you can read through the rest of documentation.

Integrations

License

Licensed under MIT license. See LICENSE for details.

Logo / icon under CC0 1.0 Universal (CC0 1.0) Public Domain Dedication (Archived page)

Comments
  • Add logo option to Endroid's provider

    Add logo option to Endroid's provider

    I know you suggested more constructor arguments, but after implementing and trying to use, I saw it wouldn't make much sense... Also, I understood you wanted to keep the original constructor as-is, with the logo being a deliberately and rare optional choice.

    Thus, the method suits just fine, keeping everything at the same place, being less verbose and less bloated (otherwise a common call + logo would need to skip-guess all the default parameters, such as colors, margin, correction level...).

    P.S.: I'd suggest creating a new release! The two external providers are only available in master.

    opened by igorsantos07 20
  • integrate bacon qr code

    integrate bacon qr code

    To assist with #37 and also to improve my own project, I have written a provider for BaconQrCode.

    I have used the current version which relies on PHP 7.1 at minimum. It is also possible to customise the QR code slightly.

    Usage:

    $provider = new \RobThree\Auth\Providers\Qr\BaconQrCodeProvider();
    $provider->setBorderWidth(1);
    $provider->setBackgroundColour('#d0d0d0');
    $provider->setForegroundColour('#333');
    
    $twoFa = new TwoFactorAuth($issuer, 6, 30, 'sha1', $provider);
    
    // works with standard usage
    $twoFa->getQRCodeImageAsDataUri($label, $secret, 400);
    
    // also access an SVG
    $provider->getQRCodeSvg($twoFa->getQRText($label, $secret), 400);
    

    As an aside, would you consider allowing setters in the main TwoFactorAuth class to allow setting the providers without declaring all the other options in the constructor?

    opened by willpower232 20
  • VerifyCode returns false / ensureCorrectTime issue

    VerifyCode returns false / ensureCorrectTime issue

    Hello, I was trying to implement your library into my project. The QR Code as well as the Code are being generated properly but I can't verify the Code.

    After looking at the code I thought about, that the Time could be an issue. After trying the code try { $tfa->ensureCorrectTime(); echo 'Your hosts time seems to be correct / within margin'; } catch (RobThree\Auth\TwoFactorAuthException $ex) { echo '<b>Warning:</b> Your hosts time seems to be off: ' . $ex->getMessage(); }

    I get the following error Uncaught Exception: Connection refused extern/lib/Providers/Time/NTPTimeProvider.php Zeile 40 Backtrace #0 extern/lib/TwoFactorAuth.php(157): RobThree\Auth\Providers\Time\NTPTimeProvider->getTime() #1 extern/2fa.php(39): RobThree\Auth\TwoFactorAuth->ensureCorrectTime() #2 {main}

    NTPTimeProvider.php /* Receive response and close socket */ if (socket_recv($sock, $recv, 48, MSG_WAITALL) === false) throw new \Exception(socket_strerror(socket_last_error($sock))); socket_close($sock);

    So it's probably an Time issue I can't verify.

    Also do I set the discrepancy in the TwoFactorAuth.php like this public function verifyCode($secret, $code, $discrepancy = 4, $time = null, &$timeslice = 0)

    or in my file with $Ergebnis= $tfa->verifyCode($secret, $_POST['verification'], $discrepancy);

    Many regards Lukas

    question 
    opened by luggesexe 18
  • Newly generated secrets failing to verify codes

    Newly generated secrets failing to verify codes

    Hello,

    I have been using your library in production for a couple of years now with no issue. We have had a bug come in where a user moving from non-2FA to 2FA could not get their code to verify. There is no issue with existing users verifying already set up codes.

    I could reproduce this on production where neither the barcode nor the generated code would generate me an accepting code. I cannot reproduce it locally. I have also found that it works perfectly on our demo environment but the same problem occurs on our test/staging environment.

    All servers are running robthree/twofactorauth version 1.8. All servers are running PHP 7.4 though there are minor differences between minor versions PHP 7.4.27 (ubuntu 18) where the issuing is occurring, PHP 7.4.14 (ubuntu 18), 7.4.16 (windows 10) where the problem doesn't appear.

    I have tried swapping out IRNGProvider and constructing with HttpTimeProvider, all of which work beautifully on the already working environments but return false from TwoFactorAuth::verifyCode on the affected environments.

    I am struggling to think what I could be missing, some php packages that are required but not installed on the affecting environments? I would have hoped that any changes in the way underlying PHP functions (thinking random_bytes) work would have bene ruled out by swapping out Providers.

    Any thoughts on this appreciated or indeed any "this is not enough info! we require x,y and z to help"- I've not bothered with code samples since the codes does work on "good" environments and the code itself is consistent across the environments. I just can't think what environmental component I may be missing that would explain the behaviour of existing codes verifying but newly generated ones not.

    opened by matthewc83 13
  • How to migrate to new server

    How to migrate to new server

    I have migrated my website to a new server.

    Now the 2fa verification always fails (verifyCode returns 0);

    How can I find out why and how to solve it? I don't want all my users to set it up again....

    What changed: Moved from php 7.4 to php 8.0.25 Moved from utf8 to utf8mb4 Moved to a different timezone

    opened by Tsjippy 11
  • Google / MS Authenticator

    Google / MS Authenticator

    I write this hesitatingly as I'm not convinced that this is an issue with this code or not, but would like to throw out issues that we've started experiencing over the past few weeks. We use this library (1.7.0)to generate and authenticate using a QR code only but have experienced the following when using Google Authenticator (GA), Microsoft Authenticator (MA) and Duo (D).

    1. If a user is using an Android phone, GA, MA and D all work flawlessly when presented with the QR code and entering the PIN.
    2. If a user is using an IOS phone, then GA regularly has issues. MA and D work OK

    Due to (2) we've been using both an IOS and Android based device to scan the same QR code, and using all three authenticators. The results are haphazard and don't appear to be following any logic, but we experience

    1. Sometimes IOS with GA manages to scan the code without any issues at all
    2. Sometimes IOS with GA scans the QR code but when entering in the same PIN as Android shows, the PIN gets rejected
    3. Sometimes IOS with GA scans the QR code but shows a completely different PIN as the Android does

    All servers have NTP configured and checks no more than every 30 sec intervals. The devices themselves are configured in the same timezone and we've confirmed that their system times are within 1sec of each other.

    So - I'm at a bit of a loss. I appreciate that we're not using the latest version but I find it odd that all of a sudden we've started seeing these issues. Yes I appreciate that it might be a problem with GA, but thought I would check in here first to see if this was a known issue (I didn't find anything) and there's nothing like getting advice from the horses' mouth, as it were.

    opened by D4V3M0NK 10
  • Location of MyProvider class when using phpqrcode and composer

    Location of MyProvider class when using phpqrcode and composer

    Am loving the fact that this is so easy to use, many congratulations sir.

    I have one question regarding the MyProvider.php class location when using PHPQRCode as per qr-code-providers

    1. I've placed the phpqrcode.php file in the same (composer) folder as TwoFactorAuth.php (./vendor/robthree/twofactorauth/lib)

    2. I've created the MyProvider.php file in the Providers/Qr folder (./vendor/robthree/twofactorauth/lib/Providers/Qr/MyProvider.php).

      1. The notes refer to that file named as myprovider.php when creating it, but I believe it should be MyProvider.php?
      2. I also believe that the namespace should be placed above the require/require_once?
    3. I've then taken your demo page, added my composer autoload.php to it and tried to get it working, but every time I attempt to run it, I get a missing phpqrcode.php file

    Warning: require_once(../../phpqrcode.php): failed to open stream: No such file or directory in /var/www/vendor/robthree/twofactorauth/lib/Providers/Qr/MyProvider.php on line 3

    Fatal error: require_once(): Failed opening required '../../phpqrcode.php' (include_path='.:/usr/share/php:/var/www/html/inc') in /var/www/vendor/robthree/twofactorauth/lib/Providers/Qr/MyProvider.php on line 3

    • Am I missing something really obvious here?

    • Should I not have placed those files in the vendor folder, but elsewhere in my application?

    • I've attached a screenshot of my vendor folder structure in the hope that assists? Screenshot from 2020-04-27 11-34-20

    question 
    opened by D4V3M0NK 10
  • Fix compatibility with endroid/qr-code 4

    Fix compatibility with endroid/qr-code 4

    Closes #82

    This PR adds compatibility with endroid/qr-code:^4 while maintaining support for older versions.

    Test code:

    <?php
    
    use RobThree\Auth\Providers\Qr\EndroidQrCodeProvider;
    use RobThree\Auth\Providers\Qr\EndroidQrCodeWithLogoProvider;
    
    require_once(__DIR__ . '/vendor/autoload.php');
    
    $filename = method_exists(\Endroid\QrCode\QrCode::class, 'create') ? 'test2.png' : 'test1.png';
    
    $provider = new EndroidQrCodeProvider();
    file_put_contents(__DIR__ . '/' . $filename, $provider->getQRCodeImage('foobar', 80));
    
    $provider2 = new EndroidQrCodeWithLogoProvider();
    $provider2->setLogo(__DIR__ . '/logo.jpeg', [30, 30]);
    file_put_contents(__DIR__ . '/logo-' . $filename, $provider2->getQRCodeImage('foobar', 80));
    

    logo.jpeg: logo

    endroid/qr-code:^3 results: test1

    logo-test1

    endroid/qr-code:^4 result: test2

    logo-test2

    opened by MasterOdin 9
  • Support for different authenticator versions?

    Support for different authenticator versions?

    I like this library. I have implemented TFA in my application and in all my tests, it seemed to work just fine.

    I was testing with a couple of different iPhones using the Google Authenticator app, very straightforward.

    However, upon deploying, the first user was using an older android phone. She installed Authenticator and took the picture of the QR. It 'seemed' to work, but Authenticator was showing a 6 digit code with a 30 seconds timeout (I have configured for an 8 digit code with a 1 minute timeout). Of course, the code does not work.

    Has anybody seen anything similar? Are there different versions of Google Authenticator (there didn't seem to be when we installed it) I should be aware of?

    Suggestions appreciated, we're 95% there!

    Thanks for all the work on this!

    question 
    opened by judodan 9
  • Demo Always fails.

    Demo Always fails.

    I've copied the demo into a laravel 5.1 view. Every time i load the page i get this line

    When aforementioned code (893875) was entered, the result would be: FAIL
    

    Obviously each time i refresh the code changes but it still fails. Only change i made in the demo was to remove

    require_once 'loader.php';
    Loader::register('../lib','RobThree\\Auth');
    

    Since laravel will load the package.

    bug fixed 
    opened by toddmcbrearty 9
  • convert issuer to string prevents php 8.1 errors

    convert issuer to string prevents php 8.1 errors

    By forcing $this->issuer to be string, even if null is set, it prevents throwing errors in PHP 8.1 is rawurlencode is not allowed to have null as parameter.

    It would be better to force string to be already in __construct, but this may create a breaking change for existing users.

    opened by brainfoolong 8
  • Move to PHP 8.1 minimum version, add typing

    Move to PHP 8.1 minimum version, add typing

    As discussed in #63, here is a set of changes to bring this lib into modern PHP.

    I'll leave this as a draft for now, as it's not 100% complete, but this gives you an opportunity to start the review process and leave comments.

    ~Nico

    opened by NicolasCARPi 4
  • Account name in MS Authenticator

    Account name in MS Authenticator

    Firstly, thanks for this library, very useful and easy to use.

    When I initialize the class and specify a name ( i.e. $tfa = new TwoFactorAuth('My App'); ) MS Authenticator doesn't seem to apply this and uses the domain name of the email address as the account name on its authenticator app.

    On the other hand, Google Authenticator works fine with this.

    Any ideas?

    wontfix 
    opened by ubay25 14
  • Thoughts about type hinting and supporting old php versions

    Thoughts about type hinting and supporting old php versions

    Hello,

    First, thank you for providing this library, I use it in my project: eLabFTW: the open source lab notebook :heart:

    I see that the minimum version for php is 5.6. Does it really makes sense to support a version that has been out of the game for 2 years now?

    See my arguments:

    By requiring a modern php version you push admins to update their stack and increase global internet security ®, but more importantly you can move forward with your codebase and use modern features (that are not even new anymore) and make your life easier as a developer.

    With that you open the door to better static analysis, and (this is why I'm here) users of the library can also type hint properly their code. My codebase is fully typed, except for getQRCodeImage ;)

    Also, if users are still using php 5.6, it's quite unlikely that they regularly update their dependencies, so the argument of "but there are still people using 5.6 out there!" is moot IMHO. In the era of containers, one has no valid excuse for keeping around old php versions (except time and money of course, but that's another debate).

    Please kindly indicate what are your reasons for supporting old php versions and if you'd consider dropping old versions in order to allow yourself and contributors to improve gradually the codebase with modern php language constructs, operators and features (and incidently, allow me to full type hint my code ;) ).

    I'm willing to contribute to this work with PRs.

    Best, ~Nico

    PS: this blog post is an interesting read

    discussion vnext 
    opened by NicolasCARPi 39
  • Image support for FreeOTP

    Image support for FreeOTP

    Feature added

    Added Image support for FreeOPT as explained on this StackOverflow answer: https://stackoverflow.com/a/50410063

    Feature test

    Feature tested on FreeOTP and works as expected. Also tested on Microsoft Authenticator, Authy and Google Authenticator to check that still works on authenticators that do not suport the image parameter.

    Test were made on Android versions only

    enhancement discussion vnext 
    opened by jmoleiro 2
Releases(1.8.2)
Owner
Rob Janssen
Software Engineer @KeenSystemsNL
Rob Janssen
Rinvex Authy is a simple wrapper for @Authy TOTP API, the best rated Two-Factor Authentication service for consumers, simplest 2fa Rest API for developers and a strong authentication platform for the enterprise.

Rinvex Authy Rinvex Authy is a simple wrapper for Authy TOTP API, the best rated Two-Factor Authentication service for consumers, simplest 2fa Rest AP

Rinvex 34 Feb 14, 2022
Redirects any user which hasn't setup two factor authentication yet to /2fa/

force-two-factor Redirects any user which hasn't setup two factor authentication yet to /2fa/. Use together with the forked two-factor plugin at https

Aiwos 0 Dec 24, 2021
API stubs for developing a plugin that provides a 2FA authentication factor in JobRouter®.

Authentication Factor API JobRouter® is a scalable digitisation platform which links processes, data and documents. Starting with JobRouter® 5.2, a se

JobRouter 4 Nov 4, 2021
Vendor-Agnostic Two-Factor Authentication

Multi-Factor Designed to be a vendor-agnostic implementation of various Two-Factor Authentication solutions. Developed by Paragon Initiative Enterpris

Paragon Initiative Enterprises 139 Dec 21, 2022
Secure WordPress login with two factor authentication

This plugin allows you to secure your WordPress login with two factor authentication. The users will have to enter a one time password every time they log in.

Volodymyr Kolesnykov 6 Nov 2, 2022
A simple two factor authentication for laravel applications

Laravel 2fa A simple two factor authentication for laravel applications. Installation Require via composer Update database Replace authentication trai

Rezkonline 1 Feb 9, 2022
Laravel Two-Factor Authentication

This package allow you to enable two-factor authentication in your Laravel applications very easily, without the need to add middleware or any modification to your routes. It stores tokens in your database in a distinct table, so you don't need to alter your users table. Notify users about their token via mail, SMS or any custom channel.

null 7 Jun 24, 2022
Google Two-Factor Authentication Package for Laravel

Google2FA for Laravel Google Two-Factor Authentication Package for Laravel Google2FA is a PHP implementation of the Google Two-Factor Authentication M

Antonio Carlos Ribeiro 785 Dec 31, 2022
Two-Factor Authentication for all your users out-of-the-box.

Two Factor On-premises Two-Factor Authentication for all your users out of the box. use Illuminate\Support\Facades\Auth; use Laragear\TwoFactor\TwoFac

Laragear 105 Dec 22, 2022
PHP class to generate and verify Google Authenticator 2-factor authentication

Google Authenticator PHP class Copyright (c) 2012-2016, http://www.phpgangsta.de Author: Michael Kliewe, @PHPGangsta and contributors Licensed under t

Michael Kliewe 2.1k Jan 2, 2023
This repository includes a sample project to illustrate the usage of the JobRouter® Authentication Factor API.

JR 2FA Example Plugin This repository includes a sample project to illustrate the usage of the JobRouter® Authentication Factor API. It can be used as

JobRouter 4 Sep 10, 2021
Multi-factor Authentication using a Public PGP key for web based applications

PGPmfa() a PHP Class for PGP Multi-factor Authentication using a Public PGP key for web based applications Multi-factor Authentication with PGP Second

null 2 Nov 27, 2022
phpCAS is an authentication library that allows PHP applications to easily authenticate users via a Central Authentication Service (CAS) server.

phpCAS is an authentication library that allows PHP applications to easily authenticate users via a Central Authentication Service (CAS) server.

Apereo Foundation 780 Dec 24, 2022
It's a Laravel 8 authentication markdown that will help you to understand and grasp all the underlying functionality for Session and API Authentication

About Auth Starter It's a Laravel 8 authentication markdown that will help you to understand and grasp all the underlying functionality for Session an

Sami Alateya 10 Aug 3, 2022
php database agnostic authentication library for php developers

Whoo Whoo is a database agnostic authentication library to manage authentication operation easily. Whoo provides you a layer to access and manage user

Yunus Emre Bulut 9 Jan 15, 2022
Library to manage HTTP authentication with PHP. Includes ServiceProviders for easy Laravel integration.

Intervention HttpAuth Library to manage HTTP authentication with PHP. Includes ServiceProviders for easy Laravel integration. Installation You can ins

null 69 Jul 14, 2022
Laravel web rest api authentication library (PHP).

Webi auth library Laravel web rest api authentication library. Install (laravel 9, php 8.1) First set your .env variables (mysql, smtp) and then compo

Atomjoy 2 Nov 25, 2022
Authentication and authorization library for Codeigniter 4

Authentication and Authorization Library for CodeIgniter 4. This library provides an easy and simple way to create login, logout, and user registratio

Rizky Kurniawan 12 Oct 10, 2022