yii2.0权限控制 ACF权限--登录验证
更新:HHH   时间:2023-1-7


ACF是一种通过yii\filters\AccessControl类来实现的简单授权

一般在控制器中我们调用如下:
打开backend\controller\SiteController.php 我们看到这样一段代码

public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'index'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}

几个必须到配置:
1、配置验证类User

'user' => [
'identityClass' => 'common\models\Usermember',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
'loginUrl'=>'/public/login'
],

2、继承IdentityInterface接口
一般来说,从数据库查找数据,只需要继承AR类即可,但是,我们这个是用户登录模型,核心是验证,所以自然需要实现核心的验证功能,就像LoginForm模型提到的validatePassword一样,实际的验证逻辑是在当前的User模型完成的。一般来说,实现IdentityInterface接口,需要实现以下方法:

public static function findIdentity($id); //①

public static function findIdentityByAccessToken($token, $type = null);   //②

public function getId();    //③

public function getAuthKey();   //④

public function validateAuthKey($authKey);    //⑤

3、登录到login()做相关调用验证:

public function login()
{
if ($this->validate()) {
if($this->rememberMe)
{
$this->_user->generateAuthKey();//③
}
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 36002430 : 0);
}
return false;
}

4、对用到控制器类做配置

/**

  • {@inheritdoc}
    */
    public function behaviors()
    {
    return [
    'access' => [
    'class' => AccessControl::className(),
    'only' => ['userhome', 'signup'],
    'rules' => [
    [
    'actions' => ['','signup'],
    'allow' => true,
    'roles' => ['?'],
    ],
    [
    'actions' => ['userhome'],
    'allow' => true,
    'roles' => ['@'],
    ],
    ],
    ],
    'verbs' => [
    'class' => VerbFilter::className(),
    'actions' => [
    'logout' => ['post'],
    ],
    ],
    ];
    }
返回web开发教程...