vxm / yii2-mfa
为yii2提供多因素认证
1.0.1
2020-06-23 16:29 UTC
Requires
- php: >=7.1
- spomky-labs/otphp: ^9.0
- yiisoft/yii2: >=2.0.13
This package is auto-updated.
Last update: 2024-09-24 16:41:45 UTC
README
关于它
一个基于Spomky-Labs/otphp
包装器的扩展,用于实现基于Yii2用户组件的多因素认证。
要求
安装
使用Composer安装Yii2 MFA
composer require vxm/yii2-mfa
使用方法
应用配置
'components' => [ 'user' => [ 'as mfa' => [ 'class' => 'vxm\mfa\Behavior', 'verifyUrl' => 'site/mfa-verify' // verify action, see bellow for setup it ] ], ]
身份实现
当使用它时,你的身份类必须实现vxm\mfa\IdentityInterface
接口,该接口继承自yii\web\IdentityInterface
,并添加getMfaSecretKey()
方法,该方法返回用于生成和验证otp的身份mfa密钥,如果身份上禁用了mfa,则返回null。
use yii\db\ActiveRecord; use vxm\mfa\IdentityInterface; /** * @property string $mfa_secret */ class User extends ActiveRecord implements IdentityInterface { public function getMfaSecretKey() { return $this->mfa_secret; } }
验证操作配置
此操作用于在用户登录并需要验证mfa otp时重定向用户。在controller
的actions
方法中配置它。
public function actions() { return [ 'mfa-verify' => [ 'class' => 'vxm\mfa\VerifyAction', 'viewFile' => 'mfa-verify', // the name of view file use to render view. If not set an action id will be use, in this case is `mfa-verify` 'formVar' => 'model', // the name of variable use to parse [[\vxm\mfa\OtpForm]] object to view file. 'retry' => true, // allow user retry when type wrong otp 'successCallback' => [$this, 'mfaPassed'], // callable call when user type valid otp if not set [[yii\web\Controller::goBack()]] will be call. 'invalidCallback' => [$this, 'mfaOtpInvalid'], // callable call when user type wrong otp if not set and property `retry` is false [[yii\web\User::loginRequired()]] will be call, it should be use for set flash notice to user. 'retry' => true, // allow user retry when type wrong otp ] ]; }
验证操作视图
/** * @var \vxm\mfa\OtpForm $model */ use yii\helpers\Html; use yii\widgets\ActiveForm; $form = ActiveForm::begin(); echo Html::tag('h1', 'Multi factor authenticate'); echo $form->field($model, 'otp'); echo Html::submitButton('Verify'); ActiveForm::end();
认证器二维码小部件
配置完成后,当用户启用mfa(设置了mfaSecretKey)时,您需要为类似谷歌认证器这样的应用提供一个二维码以生成otp。使用vxm\mfa\QrCodeWidget
在视图中渲染二维码图像。
use vxm\mfa\QrCodeWidget; echo QrCodeWidget::widget([ 'label' => Yii::$app->user->identity->email, 'issuer' => Yii::$app->name ]);
注意:当使用此小部件时,请确保用户已登录,否则将抛出
yii\base\InvalidCallException
异常。