chillerlan/php-googleauth

该软件包已被废弃且不再维护。作者建议使用chillerlan/php-authenticator软件包。

基于计数器和时间的双因素认证代码生成器(Google Authenticator)。PHP 8.2+

资助软件包维护!
Ko-Fi

5.2.1 2024-07-16 23:53 UTC

This package is auto-updated.

Last update: 2024-07-17 01:59:33 UTC


README

基于计数的(RFC 4226)和时间基础的(RFC 6238)一次性密码(OTP)生成器。(也称为另一个Google Authenticator实现!)

PHP Version Support version License GitHub actions workflow Coverage Codacy Downloads

文档

需求

安装

需要composer

通过终端:composer require chillerlan/php-authenticator

composer.json

{
	"require": {
		"php": "^8.2",
		"chillerlan/php-authenticator": "dev-main"
	}
}

注意:将dev-main替换为版本约束,例如^5.0 - 请参阅发行版以获取有效版本

成功!

使用方法

创建一个密钥

通常在用户控制面板的激活过程中创建一次密钥。因此,您只需以方便的方式将其显示给用户(例如文本字符串和QR码),并将其保存在与用户数据相关联的地方。

use chillerlan\Authenticator\{Authenticator, AuthenticatorOptions};

$options = new AuthenticatorOptions;
$options->secret_length = 32;

$authenticator = new Authenticator($options);
// create a secret (stored somewhere in a *safe* place on the server. safe... hahaha jk)
$secret = $authenticator->createSecret();
// you can also specify the length of the secret key, which overrides the options setting
$secret = $authenticator->createSecret(20);
// set an existing secret
$authenticator->setSecret($secret);

使用Authenticator::createSecret()创建的密钥也将内部存储,因此您无需在后续操作中提供当前实例中刚刚创建的密钥。

验证一次性代码

现在在登录过程中 - 用户成功输入凭据后 - 您将要求他们提供一次性代码以检查您的用户数据库中的密钥。

// verify the code
if($authenticator->verify($otp)){
	// that's it - 2FA has never been easier! :D
}

基于时间的(TOTP)

验证相邻代码

// try the first adjacent
$authenticator->verify($otp, time() - $options->period); // -> true
// try the second adjacent, default is 1
$authenticator->verify($otp, time() + 2 * $options->period); // -> false
// allow 2 adjacent codes
$options->adjacent = 2;
$authenticator->verify($otp, time() + 2 * $options->period); // -> true

基于计数的(HOTP)

// switch mode to HOTP
$options->mode = AuthenticatorInterface::HOTP;
// user sends the OTP for code #42, which is equivalent to
$otp = $authenticator->code(42); // -> 123456
// verify [123456, 42]
$authenticator->verify($otp, $counterValueFromUserDatabase) // -> true

URI创建

为了显示适用于移动认证器的QR码,您需要一个otpauth:// URI,可以通过以下方法创建。

  • $label应该是可以识别密钥所属账户的内容
  • $issuer是您的网站或公司名称等,这样用户就可以识别多个账户。
$uri = $authenticator->getUri($label, $issuer);

// -> otpauth://totp/my%20label?secret=NKSOQG7UKKID4IXW&issuer=chillerlan.net&digits=6&period=30&algorithm=SHA1

注意事项

请记住,不是所有认证器都认可几个URI设置。请参阅Google Authenticator维基获取更多信息。

// code length, currently 6 or 8
$options->digits = 8;
// valid period between 15 and 60 seconds
$options->period = 45;
// set the HMAC hash algorithm
$options->algorithm = AuthenticatorInterface::ALGO_SHA512;

API

认证器

认证器选项

属性

认证器接口

方法

常量

2FA ALL THE THINGS!