Anil Kumar
Anil Kumar

Reputation: 711

yii2 CSRF not validating host

One more issue I am facing my site is created in yii2 and CSRF is enabled but when I copy full form including csrf token and create new html file outside server and submit form from outside of server it accepting my form.

What is the expected result?

it should give permission issue

What do you get instead?

it successfully accepting form not sure either I am missing any configuration or what

Yii version 2.0.6

PHP version 5.5.38

Operating system CentOS release 6.9 (Final)

Upvotes: 1

Views: 808

Answers (2)

rob006
rob006

Reputation: 22174

CSRF protection is based on the fact, that third party website should not know CSRF token of your user. If you expose CSRF token, then the whole protection will not work. This is by design.

If you want to block requests from untrusted domains, you should probably use CORS.

Upvotes: 2

Chux
Chux

Reputation: 1227

That's happening because, as you said, you are using CRSF. If you want to accept data from another domain, you'll need to disable CRSF at least for that particular request. Either this way:

class MyController extends Controller
{
    public $enableCsrfValidation = false;

or this way:

class MyController extends Controller
{
    public function beforeAction($action)
    {
        if (in_array($action->id, ['incoming'])) {
            $this->enableCsrfValidation = false;
        }
        return parent::beforeAction($action);
    }

From the cookbook: https://yii2-cookbook.readthedocs.io/csrf/

And also, from the official docs: https://www.yiiframework.com/doc/api/2.0/yii-web-controller#$enableCsrfValidation-detail

Upvotes: 1

Related Questions