how to limit access url view on yii2 by id

a 夏天 提交于 2020-01-05 04:05:17

问题


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???


回答1:


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  



回答2:


There are AccessControlFilters for doing this



来源:https://stackoverflow.com/questions/38661844/how-to-limit-access-url-view-on-yii2-by-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!