Google authenticator api php

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

PHP class to generate and verify Google Authenticator 2-factor authentication

License

Vectorface/GoogleAuthenticator

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Читайте также:  Найти повторяющиеся символы в строке python

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Google Authenticator (TOTP)

  • Uses https://github.com/endroid/qr-code to generate QR code data URIs
  • No longer generates Google’s Chart API to make QR code links
  • Uses namespacing
  • Augmented test coverage to 100%
  • Bumped minimum PHP version to 7.3
  • Copyright (c) 2012-2016, http://www.phpgangsta.de
  • Author: Michael Kliewe, @PHPGangsta and contributors
  • Licensed under the BSD License.

This PHP class can be used to interact with the Google Authenticator mobile app for 2-factor-authentication. This class can generate secrets, generate codes, validate codes and present a QR-Code for scanning the secret. It implements TOTP according to RFC6238

For a secure installation you have to make sure that used codes cannot be reused (replay-attack). You also need to limit the number of verifications, to fight against brute-force attacks. For example you could limit the amount of verifications to 10 tries within 10 minutes for one IP address (or IPv6 block). It depends on your environment.

 require_once 'vendor/autoload.php'; use Vectorface\GoogleAuthenticator; $ga = new GoogleAuthenticator(); $secret = $ga->createSecret(); echo "Secret is: $secret>\n\n"; $qrCodeUrl = $ga->getQRCodeUrl('Blog', $secret); echo "PNG Data URI for the QR-Code: $qrCodeUrl>\n\n"; $oneCode = $ga->getCode($secret); echo "Checking Code '$oneCode' and Secret '$secret':\n"; // 2 = 2*30sec clock tolerance $checkResult = $ga->verifyCode($secret, $oneCode, 2); if ($checkResult) < echo 'OK'; > else < echo 'FAILED'; >

Running the script provides output similar to:

Secret is: OQB6ZZGYHCPSX4AK PNG Data URI for the QR-Code: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAARgAAAEYCAIAAAAI[snipped] Checking Code '848634' and Secret 'OQB6ZZGYHCPSX4AK': OK 

composer require vectorface/googleauthenticator

  • All tests are inside tests folder.
  • Execute composer install to prepare your environment.
  • Run composer test from the project root directory.

About

PHP class to generate and verify Google Authenticator 2-factor authentication

Источник

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

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

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

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

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

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

FixedByteNotation.php GoogleAuthenticator.php 
require_once('GoogleAuthenticator.php'); 
$ga=new GoogleAuthenticator; $user->ga_secret=$ga->generateSecret(); $user->save(); 

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

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

$ga=new GoogleAuthenticator; $ga->getUrl($user->login,'mysite.com',$user->ga_secret); 

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

$url = sprintf("otpauth://totp/%s?secret=%s", $alias, $secret); $encoder = 'https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl='; $qrImageURL = sprintf( "%s%s",$encoder, urlencode($url)); 
$ga=new GoogleAuthenticator; $code=$ga->getCode($user->ga_secret); if ($code!=$_POST['code']) return new AuthError('invalid code'); 

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

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

Демонстрационная версия доступна по адресу googleauth.phpbee.org/users

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

PHP class to generate and verify Google Authenticator 2-factor authentication

License

PHPGangsta/GoogleAuthenticator

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Guess I have to install phpunit for composer, and use a modern version of it (namespaces and so on). But not today.

Git stats

Files

Failed to load latest commit information.

README.md

Google Authenticator PHP class

  • Copyright (c) 2012-2016, http://www.phpgangsta.de
  • Author: Michael Kliewe, @PHPGangsta and contributors
  • Licensed under the BSD License.

Build Status

This PHP class can be used to interact with the Google Authenticator mobile app for 2-factor-authentication. This class can generate secrets, generate codes, validate codes and present a QR-Code for scanning the secret. It implements TOTP according to RFC6238

For a secure installation you have to make sure that used codes cannot be reused (replay-attack). You also need to limit the number of verifications, to fight against brute-force attacks. For example you could limit the amount of verifications to 10 tries within 10 minutes for one IP address (or IPv6 block). It depends on your environment.

 require_once 'PHPGangsta/GoogleAuthenticator.php'; $ga = new PHPGangsta_GoogleAuthenticator(); $secret = $ga->createSecret(); echo "Secret is: ".$secret."\n\n"; $qrCodeUrl = $ga->getQRCodeGoogleUrl('Blog', $secret); echo "Google Charts URL for the QR-Code: ".$qrCodeUrl."\n\n"; $oneCode = $ga->getCode($secret); echo "Checking Code '$oneCode' and Secret '$secret':\n"; $checkResult = $ga->verifyCode($secret, $oneCode, 2); // 2 = 2*30sec clock tolerance if ($checkResult) < echo 'OK'; > else < echo 'FAILED'; >

Running the script provides the following output:

Secret is: OQB6ZZGYHCPSX4AK Google Charts URL for the QR-Code: https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/infoATphpgangsta.de%3Fsecret%3DOQB6ZZGYHCPSX4AK Checking Code '848634' and Secret 'OQB6ZZGYHCPSX4AK': OK 
  • Composer will take care of autoloading the library. Just include the following at the top of your file require_once __DIR__ . ‘/../vendor/autoload.php’;
  • All tests are inside tests folder.
  • Execute composer install and then run the tests from project root directory
  • Run as phpunit tests from the project root directory

If you like this script or have some features to add: contact me, visit my blog, fork this project, send pull requests, you know how it works.

About

PHP class to generate and verify Google Authenticator 2-factor authentication

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

PHP SDK for Google Authenticator

License

iamirnet/google-authenticator

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Google Authenticator with PHP

Google Authenticator generates 2-Step Verification codes on your phone.

2-Step Verification provides stronger security for your Google Account by requiring a second step of verification when you sign in. In addition to your password, you’ll also need a code generated by the Google Authenticator app on your phone.

Learn more about 2-Step Verification: https://g.co/2step

composer require iamirnet/google-authenticator 

If the above step didn’t work, install composer and try again.

sudo apt-get install curl php-curl curl -s http://getcomposer.org/installer | php php composer.phar install 

Composer not found? Use this command instead:

php composer.phar require "iamirnet/google-authenticator" 

Download and install composer:

  1. https://getcomposer.org/download/
  2. Create a folder on your drive like C:\iAmirNet\GoogleAuthenticator
  3. Run command prompt and type cd C:\iAmirNet\GoogleAuthenticator
  4. composer require iamirnet/google-authenticator
  5. Once complete copy the vendor folder into your project.

composer require iamirnet/google-authenticator

require 'vendor/autoload.php'; // config by specifying api key and secret $ga = new \iAmirNet\GoogleAuthenticator\Authenticator(" "," ");
/** * Create a new random secret for the Google Authenticator app. * 16 characters, randomly chosen from the allowed Base32 characters * equals 10 bytes = 80 bits, as 256^10 = 32^16 = 2^80 */ print_r($ga->create($issuer = null, $label = null, $width = 200, $height = 200));
Array ( 'secret' => 'ILY3AYQEAPUZBUQM', 'qr' => 'https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/iAmirNet?secret=ILY3AYQEAPUZBUQM&issuer=iAmirNet' ) 
//Check the verification code entered by the user. print_r($ga->verify($secret, $pin, $relaxed = 'enabled', $last = '')); // return false or time correct
  • Give us a star ⭐
  • Fork and Clone! Awesome
  • Select existing issues or create a new issue and give us a PR with your bugfix or improvement after. We love it ❤️

Источник

Оцените статью