Yii2 global filter/behavior to force user to authenticate first(Yii2 全局过滤器/行为强制用户首先进行身份验证)
问题描述
在我的 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 全局过滤器/行为强制用户首先进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Yii2 全局过滤器/行为强制用户首先进行身份验证
基础教程推荐
- PHP 类:全局变量作为类中的属性 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何替换eregi() 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
