在我的 Yii2 应用程序中,我试图强制所有用户进行身份验证.如果他们尚未通过身份验证,则应将其重定向到登录页面.
In my Yii2 application I'm trying to force all users to be authenticated. If they're not already authenticated they should be redirected to the login page.
在 Yii1 中,我通过创建一个类来检查用户是否登录并将该类附加到我的主配置文件中的 onBeginRequest
行为.
In Yii1 I did this by creating a class that would check if a user was logged in and attaching that class to the onBeginRequest
behavior in my main config file.
// Yii 1
'behaviors' => array(
'onBeginRequest' => array(
'class' => 'application.components.RequireLogin',
)
),
如何在 Yii2 中获得相同的行为?我知道我可以使用行为来做到这一点,但我不想将此行为添加到我的主配置文件中,因此首先检查所有请求以进行身份验证.
How can I get the same behavior in Yii2? I know I can use behavior to do this, but I wan't to add this behavior to my main config file so all requests are first checked for authentication.
工作行为方法如下所示:
The working behaviors method looks like this:
// Yii2
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'allow' => true,
'roles' => ['@'],
],
],
],
];
}
好的,所以我不得不添加以下代码下面 'components' =>[...]
Ok, so I had to add the following code below 'components' => [...]
'as beforeRequest' => [
'class' => 'yiifiltersAccessControl',
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'allow' => true,
'roles' => ['@'],
],
],
],
阅读更多关于格式的信息:http://www.yiiframework.com/doc-2.0/guide-concept-configurations.html#configuration-format
Read more about the format: http://www.yiiframework.com/doc-2.0/guide-concept-configurations.html#configuration-format
这篇关于Yii2 全局过滤器/行为强制用户首先进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!