验证用户是否具有执行某项操作的足够权限的过程称为授权。Yii提供了ACF(访问控制过滤器),这是一种实现为yii \ filters \ AccessControl的授权方法。修改SiteController的behaviors()函数-
public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'only' => ['about', 'contact'], 'rules' => [ [ 'allow' => true, 'actions' => ['about'], 'roles' => ['?'], ], [ 'allow' => true, 'actions' => ['contact', 'about'], 'roles' => ['@'], ], ], ], ]; }
在上面的代码中,ACF作为行为附加。only属性指定ACF应该仅应用于about和contact操作。所有其他动作均不受访问控制。rules属性列出了访问规则。所有来宾(具有“?”角色)将被允许访问about动作。所有经过身份验证的用户(具有“ @”角色)将被允许访问联系人和有关操作。
如果您访问URL http:// localhost:8080 / index.php?r = site / about,则会看到该页面,但如果打开URL http:// localhost:8080 / index.php?r = site / contact,您将被重定向到登录页面,因为只有经过身份验证的用户才能访问联系人操作。
访问规则支持许多选项-
步骤1 -Yii提供以下便捷的方法来使用密码。
public function actionAuth() { $password = "asd%#G3"; //generates password hasg $hash = Yii::$app->getSecurity()->generatePasswordHash($password); var_dump($hash); //validates password hash if (Yii::$app->getSecurity()->validatePassword($password, $hash)) { echo "correct password"; } else { echo "incorrect password"; } //generate a token $key = Yii::$app->getSecurity()->generateRandomString(); var_dump($key); //encrypt data with a secret key $encryptedData = Yii::$app->getSecurity()->encryptByPassword("mydata", $key); var_dump($encryptedData); //decrypt data with a secret key $data = Yii::$app->getSecurity()->decryptByPassword($encryptedData, $key); var_dump($data); //hash data with a secret key $data = Yii::$app->getSecurity()->hashData("mygenuinedata", $key); var_dump($data); //validate data with a secret key $data = Yii::$app->getSecurity()->validateData($data, $key); var_dump($data); }
步骤2-输入URL http:// localhost:8080 / index.php?r = site / auth,您将看到以下内容。