\yii\web\Request:getIsAjax()
public function getIsAjax()
{
return $this->headers->get('X-Requested-With') === 'XMLHttpRequest';
}
But, for the cross-origin ajax requests, send by browser XMLHttpRequest (or modern fetch API) dows not contains XMLHttpRequest headers.
How to reproduce:
1) configure Cors filter to allow accepting cross-origin requests.
For Apache:
Header setifempty Access-Control-Allow-Origin "*"
Header setifempty Access-Control-Allow-Methods "GET"
For Yii:
public function behaviors()
{
return ['cors' => \yii\filters\Cors::class];
}
2) send cross-origin request from browser console to different your site:
fetch('http://mysite.ru')
Request headers:
GET / HTTP/1.1
Host: mysite.ru
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Sec-Fetch-Dest: empty
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36
DNT: 1
Accept: */*
Origin: http://localhost:3000
Sec-Fetch-Site: cross-site
Sec-Fetch-Mode: cors
Referer: http://localhost:3000
Accept-Encoding: gzip, deflate, br
Accept-Language: ru,en;q=0.9,uk;q=0.8,und;q=0.7
There is no longer the usual XMLHttpRequest header, but, there are 2 new headers:
Sec-Fetch-Mode: cors and
Sec-Fetch-Site: cross-site
Yii::$app->request->isAjax give false..... I propose to add Sec-Fetch-Mode header in getIsAjax.
Because of Request::getIsAjax() is false for cors request, so authentication behavior different - it send redirects to login page for ajax requests :(
Good idea. Would you like to do a pull request?
I found a workaroud. Unlike the regular ajax-requests, where setting a X-Requested-With by hand is prohibited, in cross-origin requests - it's allowed!
fetch(url, {
method: 'GET',
headers: {'X-Requested-With': 'XMLHttpRequest'}
})
:)))
Still, checking for additional headers sounds like a good idea.
pull request sent.
This broke redirects from links of external sites.
Tried to login through Zendesk, which goes to our login page, but if you are already logged in it redirects you back automatically.
It sends
Sec-Fetch-Site: cross-site

Which tells yii it is an ajax call, which is incorrect.
Just to add some context
https://stackoverflow.com/questions/44202593/detect-a-fetch-request-in-php
There is no actual true way to detect an AJAX call
X-Requested-With was just a way some libraries identified themselves as an ajax call.
I vote to revert this back immediately.
Fixed.
Most helpful comment
Just to add some context
https://stackoverflow.com/questions/44202593/detect-a-fetch-request-in-php
There is no actual true way to detect an AJAX call
X-Requested-With was just a way some libraries identified themselves as an ajax call.
I vote to revert this back immediately.