Skip to content Skip to sidebar Skip to footer

Prevent Users From Accessing A Url Directly Yii 2

I have this piece of code that if the user clicks on it the link will be replaced by text making it unable to be clicked again. The problem now is that if the user access it direct

Solution 1:

In controller

publicfunctionbehaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'actions' => ['addsubject'],
                    'allow' => true,
                    'roles' => ['addsubject', 'yourmodelname'],
                ],
                [
                    'allow' => true,
                    'roles' => ['superAdmin', 'admin', 'managerModule1', 'managerApp'],
                ],   
            ],
        ],         
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                    'addsubject' => ['post'],
                ],
        ],

    ];
}

checkout this 2 answers also

how to deny the access of url in yii even if we know the url?

how to limit access url view on yii2 by id

In which you can understand the use of filters.

Solution 2:

Make it a POST link so that it has to clicked and can't be directly run from the browser

ie.

adding 'data-method' => 'post' to HTML::a

<?= Html::a('<b>ADD</b>',['site/addsubject',    'subjectid'=>$subjects['subjectid'], 'clientid' => $_user],['class' => 'btn-info btn-transparent btn-large', 'data-method' => 'post']) ?>

And in the Access Rules you can add rule to only accept POST Request

i.e

'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'addsubject' => ['post'],
                ],
            ],

Hope this helps. Thanks.

Edit: Below is sample for SiteController

publicfunctionbehaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => True,
                        'actions' => [],
                        'roles' => []
                    ],
                    [
                        'actions' => ['login', 'error', 'captcha'],
                        'allow' => true,
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                    'addsubject' => ['post'],
                ],
            ],
        ];
    }

Post a Comment for "Prevent Users From Accessing A Url Directly Yii 2"