如何通过id限制yii2上的访问URL视图

时间:2016-07-29 14:55:52

标签: yii2

我基本上是一名PHP开发人员&学习Yii2。我正在开发具有基于帐户的登录系统的Web应用程序。就像我在PHP Web应用程序中所做的那样,如果他/她未经过身份验证,我想阻止其他用户访问该视图。就像有人试图从外部访问url(任何相关的URL)一样:

www.example.com/permintaanbarang/index.php?r=user/view&id=1 chage to 其他用户访问www.example.com/permintaanbarang/index.php?r=user/view&id=2

当时该人应被重定向到登录页面或Not Notfound 404,因为该人无权直接访问基于帐户的页面。

在MVC框架中实现此目的的方向是什么?

2 个答案:

答案 0 :(得分:0)

执行此操作有AccessControlFilters

答案 1 :(得分:0)

控制访问并避免访客用户(未经过身份验证)访问的一种简单方法是使用过滤器进行访问控制

<?php
namespace yourapp\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use common\models\LoginForm;
use yii\filters\VerbFilter;

/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    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'],
                ],
            ],
        ];
    }

在此示例中,您可以看到您可以配置您可以访问的所有操作以及经过身份验证的@ 您可以找到有用的本指南http://www.yiiframework.com/doc-2.0/guide-security-authorization.html和此参考http://www.yiiframework.com/doc-2.0/yii-filters-accesscontrol.html

在Yii2中,您还可以使用RBAC authrization组件来定义用户类,并授予此类特定的访问规则。

您还可以根据具体需要检查RABC Auth程序,例如:

   if (!Yii::$app->user->isGuest) { // if the user is authenticated (not guest)
                if ( Yii::$app->User->can('admin') ){ // if the role is admin 

                ..... 
                you app code