Перейти к содержимому

Как подключить php 2fa

  • автор:

Getting Started

Logo

The best way of making use of this project is by installing it with composer.

or if you have composer installed globally

2. Create an instance

Now you can create an instance for use with your code

Note: if you are not using a framework that uses composer, you should include the composer loader yourself

3. Shared secrets

When your user is setting up two-factor, or multi-factor, authentication in your project, you can create a secret from the instance.

Once you have a secret, it can be communicated to the user however you wish.

Note: until you have verified the user is able to use the secret properly, you should store the secret as part of the current session and not save the secret against your user record.

4. Verifying

Having provided the user with the secret, the best practice is to verify their authenticator app can create the appropriate code.

If $result is true then your user has been able to successfully record the $secret in their authenticator app and it has generated an appropriate code.

You can now save the $secret to your user record and use the same verifyCode method each time they log in.

Двухфакторная авторизация для PHP с использованием приложения Google Authenticator

Двухфакторная авторизация используется для повышения защиты аккаунтов пользователей от несанкционированного доступа. Множество людей используют одни и те же связки логин-пароль для доступа к разным сайтам, и это может быть использовано злоумышленниками.

Включение двухфакторной авторизации на нашем сайте приведет к тому, что то при каждом новом входе система будет дополнительно запрашивать у пользователя динамический 6-значный код. Таким образом злоумышленник, завладевший логином и паролем пользователя, не сможет получить доступ к этому аккаунту.

Динамический код может быть получен разными способами, в данном случае мы рассмотрим использование программы Google Authenticator. Для добавления двухфакторной авторизации на сайт нам потребуется библиотека GoogleAuthenticator.php (автор Christian Stocker).

Пошаговая инструкция

    Добавляем библиотеку в наш проект (нужны только 2 файла из дистрибутива).

Также потребуется вывести QR-code -это позволит легко добавить ключ для нашего сайта в программу Google Authenticator.
Разумным решением также является ввод проверочного кода, это служит сигналом что пользователь успешно установил программу и для него можно включать второй фактор авторизации.

Для показа QR-кода можно воспользоваться методом getUrl класса GoogleAuthenticator.

Либо собрать адрес картинки самостоятельно.

Переменная $code должна соответствовать введенному пользователем в форму входа.

Эти несложные действия позволят повысить безопасность посетителей нашего сайта.

Easy Two Factor Authentication (2FA) with Google Authenticator & PHP

Rich Barrett

Implementing two factor authentication with PHP is easier than you think and is hugely beneficial for the security of your application.

In this article I show you how you can quickly implement 2FA with Google Authenticator (but is also compatible with other 2FA apps).

What is Two Factor Authentication?

2FA is nothing new. In fact it’s already been widely adopted by most major platforms (Facebook, Apple, Google etc) as a means of making account logins more secure.

Two Factor Authentication, also known as 2FA, two step verification or TFA (as an acronym), is an extra layer of security that is known as “multi factor authentication” that requires not only a password and username but also something that only, and only, that user has on them, i.e. a piece of information only they should know or have immediately to hand — such as a physical token.

So how does the user get the code?

  • Historically this required the user to carry a widget or card reader device (in the case of bank accounts) on their person, to generate a unique code.
  • Recently a popular method has been sending the user an SMS with a one time use code.

However there are other options…

How Google Authenticator works

Google Authenticator is a free app for your smart phone that generates a new code every 30 seconds. It works like this:

  1. When enabling 2FA, the application you’re securing generates a QR code that user’s scan with their phone camera to add the profile to their Google Authenticator app.
  2. Your user’s smart phone then generates a new code every 30 seconds to use for the second part of authentication to the application.

Implementing Google Authenticator on your website using PHP

The easiest way to do this is to use an open source composer package to do the tricky stuff for you:

Programster’s Blog

Tutorials focusing on Linux, programming, and open-source

Setting Up Google 2FA on PHP

There are actually quite a few packages for implementing two-factor-authentication in PHP but I am going to be using pragmarx/google2fa for this tutorial, simply because it has 6.26 million installs at the time of writing this tutorial. That doesn’t necessarily mean its great, but it’s a good rule of thumb.

This tutorial will focus on just adding support for 2FA in PHP. This could be for either a website, or a CLI utility. It makes no difference.

Steps

First we need to install the package, which is as easy as:

Then we can make use of it to generate a secret for our user(s).

Now you have a secret for our user(s), they can feed it into their Google authenticator application.

Now when that user wishes to authenticate, the application needs to do the following:

Taking It Further With QR Codes

The biggest problem with the solution above is that $google2fa->generateSecretKey() generates a long string that is tedious to enter into a phone manually. To get around this, we can expose a QR code to the user to make it easier to add to the authenticator application.

Install Package

First we need to install our QR code generator package.

Generate QR Code

Debugging

If you get the message:

Then you just need to make sure to install the php8.0-imagick package.

Conclusion

You should now have enough to get started with setting up 2FA in your application. This tutorial was aimed at getting you started quickly, but you may wish to read up on how you can take it further by:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *