oops / google-authenticator
Requires
- php: ^7.2
- paragonie/constant_time_encoding: ^2.0
Requires (Dev)
- mockery/mockery: ^1.3
- nette/di: ^3.0
- nette/tester: ^2.3.1
- phpstan/phpstan: ^0.12
Suggests
- nette/di: Optional integration with Nette's DI container
This package is not auto-updated.
Last update: 2022-02-01 12:41:36 UTC
README
Oops/TotpAuthenticator实现了TOTP算法,该算法允许您轻松设置两因素认证机制。简而言之,TOTP基于当前Unix时间和给定的种子(至少16个字符的base32字符串)生成一个伪随机的六位数。种子在您和移动应用之间共享,并通过QR码传递给应用。每次您需要认证用户时,请让他们输入应用生成的代码,并与您的服务器生成的代码进行验证。
安装和需求
$ composer require oops/totp-authenticator
Oops/TotpAuthenticator需要PHP >= 7.2。
用法
如果您使用Nette的DI容器,可以轻松地通过几行配置将Oops/TotpAuthenticator集成
extensions:
totp: Oops\TotpAuthenticator\DI\TotpAuthenticatorExtension
totp:
timeWindow: 1
issuer: MyApp
否则,您可以直接实例化Oops\TotpAuthenticator\Security\TotpAuthenticator
并可选地进行配置
$totpAuthenticator = (new Oops\TotpAuthenticator\Security\TotpAuthenticator) ->setIssuer('MyApp') ->setTimeWindow(1);
timeWindow
选项设置了一种宽容度,以补偿您的服务器时间和应用时间之间可能存在的差异。默认值为1,这意味着前一个或下一个30秒块的代码也将被视为有效。如果您想非常严格,可以将它设置为0,但我强烈建议不要将其设置得比1更高。
issuer
是可选的,但如果您使用一些通用值作为用户的账户名,例如他们的电子邮件地址,则非常有用。由于多个服务可以将该值用作识别用户的方式,因此您应该提供issuer
以区分您的应用在TOTP应用中的代码。
设置2FA
首先,您需要生成一个密钥——一个base32字符串——它与您和应用共享。TotpAuthenticator
提供了生成密钥的方法。密钥必须是用户唯一的,因此应将其存储在包含其他用户数据的地方,例如数据库中。只需记住要对其进行加密,因为它是非常敏感的信息。
$secret = $totpAuthenticator->getRandomSecret();
然后,您可以将密钥和唯一的账户名(例如用户的电子邮件地址)显示给用户,或者更方便地,提供包含特定格式URI的QR码。同样,TotpAuthenticator
可以为您构建URI。
$uri = $totpAuthenticator->getTotpUri($secret, $accountName);
验证
一旦用户在他们的TOTP应用中设置了账户,您可以要求他们输入6位数并轻松地对其进行验证。
if ($totpAuthenticator->verifyCode($code, $secret)) { // successfully verified } else { // incorrect code }