0

我需要在 YII 应用程序的所有页面上强制执行身份验证。为此,我SiteController使用从http://www.heirbaut.nl/2010/02/23/forcing-a-yii-application-to-authenticate/获得的以下代码扩展了该类:

/**
 * @return array action filters
 */
public function filters(){
    return array(
        'accessControl', // perform access control for CRUD operations
    );
}

/**
 * Specifies the access control rules.
 * This method is used by the 'accessControl' filter.
 * @return array access control rules
 */
public function accessRules(){
    return array(
        array('allow',  // allow all users to perform 'login'
            'actions'=>array('login'),
            'users'=>array('*'),
        ),
        array('allow', // allow authenticated user to perform any action
            'users'=>array('@'),
        ),
        array('deny',  // deny all users
            'users'=>array('*'),
        ),
    );
}

这只做了它应该做的事情,将未经身份验证的用户的所有请求重定向到登录表单,用于index.phpurl。但是index.php?r=person,因此,应用程序的主菜单绕过了这个限制,无论身份验证如何都会显示出来。

4

1 回答 1

0

每个控制器都需要引用该代码。一个选项是创建您自己的控制器,扩展CController并将其放置在您的protected/components文件夹中

class MyController extends CController{
    /**
     * @return array action filters
     */
    public function filters(){
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules(){
        return array(
            array('allow', // allow authenticated user to perform any action
                'users'=>array('@'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }
}

然后在您的控制器类中,您需要扩展MyController和覆盖accessRules()以添加任何其他规则

public class SiteController extends MyController{

    ...

    public function accessRules(){
        $rules=parent::accessRules();
        array_unshift($rules,array(
            'allow',  // allow all users to perform 'login'
            'actions'=>array('login'),
            'users'=>array('*'),
        ));
        return $rules;
    }

    ...
}
于 2013-02-09T09:27:57.687 回答