how to limit access url view on yii2 by id

2019-07-25 07:58发布

I am basically a PHP developer & learning Yii2. I am working on web application that has account based login system. Like the way i was doing in PHP web applications, i want to stop another user from accessing the view if he/she is not authenticated. Its like if someone tries to access url(any related URL) externally:

www.example.com/permintaanbarang/index.php?r=user/view&id=1 chage to www.example.com/permintaanbarang/index.php?r=user/view&id=2 by another user

At that time that person should be redirected to login page or Notice NotFound 404 as that person is not authorized to access account based page directly.

What are the directions to implement this in MVC framework???

标签: yii2
2条回答
何必那么认真
2楼-- · 2019-07-25 08:48

A simple way for controlling access and avoid to guest user (not authenticated) to access is use filter for access control

<?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'],
                ],
            ],
        ];
    }

In this sample you can see that you can configure the action you can access ofr all and for authenticated @ You can find useful this guide http://www.yiiframework.com/doc-2.0/guide-security-authorization.html and this reference http://www.yiiframework.com/doc-2.0/yii-filters-accesscontrol.html

In Yii2 you can also use a RBAC authrization component for define class of user and grant to this class specific accessing rules ..

and you can also check programmaticaly the RABC Auth for specific need eg:

   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  
查看更多
手持菜刀,她持情操
3楼-- · 2019-07-25 08:56

There are AccessControlFilters for doing this

查看更多
登录 后发表回答