behaviors() verbs allow only local requests

I use yii2 advanced. I have the following behaviors() method in my NameController:




...


class NameController extends Controller

{    

    public function behaviors()

    {

        return [

            'access' => [

                'class' => AccessControl::className(),

                'rules' => [

                    [

                        'actions' => [],

                        'allow' => true,

                        'roles' => ['?'],

                    ],

                    [

                        'actions' => [],

                        'allow' => true,

                        'roles' => ['@'],

                    ],

                ],

            ],

            'verbs' => [

                'class' => VerbFilter::className(),

                'actions' => [

                    '*' => ['get'],

                ],

            ],

        ];

    }


    ...

}



What I have now:

I am allowing any action within this NameController to be used only by GET request.

What I would like to achieve:

I want to allow only GET requests from a local server, so none of the foreign servers should be able to cURL, file_get_contents(), etc to NameController’s actions.

An example:

Let’s say my domain is http://domain.com. If I send GET request (e.g. AJAX) within this domain, than requests should be successful, even if they are coming from different controller. In case of any other domain or server trying to cURL or access actions within NameController, they should receive error (let’s say 404 header).

Questions:

Is it possible to do using behaviors()?

Or is there any special class or library in Yii2 for this?

Yes. https://github.com/yiisoft/yii2/issues/7823

Not at the moment.

Thank you very much for this reply, it is very useful.

So what I can do is check if this is an AJAX request or not and if not than this is probably request from other server/website, because I do not have headers for for allowing cross domain requests.

Is it correct?

Yes.