E
E
etterej2017-09-12 08:48:26
Yii
etterej, 2017-09-12 08:48:26

How to change the behavior that is in beforeAction?

Controller.php defines a beforeAction() (YII2) method that throws an exception if csrf validation fails. How to change this behavior, I would like me to stay on the authentication page, but at the same time a pop-up message appeared about the failed validation (I do not want to do $this->enableCsrfValidation = false). In my controller I do this:

public function beforeAction($action) {
        if ($this->enableCsrfValidation && Yii::$app->getErrorHandler()->exception === null && !Yii::$app->getRequest()->validateCsrfToken()) {
            Yii::$app->session->setFlash('info', 'Wasted');
            $this->redirect(['/']);
        }
        return parent::beforeAction($action);
    }

Of course, the exception continues to be caught.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2017-09-12
@qonand

csrf is designed to protect the site from cross-site request forgery, so if the validation fails, then it is highly likely that the request was forged, why display a pop-up message in this case? It's not logical and pointless.
But if you still want to display a popup message then don't reinvent the wheel. Make the form submit by Ajax, and at the JS level, check the response for an exception and, depending on whether it exists or not, display a pop-up message

I
Ilya Agafonov, 2017-09-12
@Tairesh

Finally read the documentation ! Everything has long been invented. If you don't need CSRF validation, just set the $enableCsrfValidation controller property to false. But, of course, you need to think a hundred times whether you really do not need it. If you are just making Ajax requests, add a CSRF token to them, which can be added to the form via
or directly in javascript add to request parameters

var params = {
    // some params
};
params[yii.getCsrfParam()] = yii.getCsrfToken();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question