oops / totp-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 auto-updated.
Last update: 2022-06-30 14:44:42 UTC
README
🏚️ 本项目已被弃用
请使用 https://github.com/jiripudil/otp 以获取更现代、功能更丰富的单次密码实现。
Oops/TotpAuthenticator实现了TOTP算法,让您可以轻松设置双因素认证机制。简而言之,TOTP根据当前Unix时间和给定的种子(至少16个字符的base32字符串)生成一个伪随机的六位数。种子由您和移动应用共享,并通过二维码传递给应用。每次您需要验证用户时,请让他们输入应用程序生成的代码,并将其与您的服务器生成的代码进行验证。
安装和需求
$ 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
是可选的,但如果您使用一些通用值作为用户账户名,例如他们的电子邮件地址,则非常有用。由于多个服务可以使用该值作为识别用户的方式,您应该在TOTP应用中提供issuer
以区分您的应用代码。
设置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 }