Request object cannot recognize cross-site's ajax request header

In my project, I use beforeExecuteRoute() to control access, code like this

public function beforeExecuteRoute(Dispatcher $dispatcher) {
        $controllerName = $dispatcher->getControllerName();

        // Check controller permissions
        if ($this->acl->isPrivate($controllerName)) {
            // Get the current identity
            $identity = $this->auth->getIdentity();
            // If user is not login then redirect the user to login page
            if (!is_array($identity)) {
                if ($this->request->isAjax()) {
                    $this->log->info('ajax');
                    $this->helper->infoShowWithJSON(-1, $this->lang->_('has_no_privilege_login'));
                    $dispatcher->setReturnedValue($this->response);
                    return false;
                } else {
                    $this->log->info('not ajax');
                    return $this->helper->infoShowWithRedirect(
                        $this->lang->_('has_no_privilege_login'),
                        'user_login',
                        2,
                        'error'
                    );
                }
            }
            ...
}

But I found that other site use ajax (which has no privilege to access), $this->request->isAjax() is not working, code like this:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>

        <script>
        $(document).ready(function() {
            $.post('http://paper.front.dev/admin/paper/generate', function($data){
                alert($data.message);
            });
        });
        </script>

The log file only logs 'no ajax'! What is the problem?

Local request works properly.



35.1k

If you modify your jquery code ?

                $.ajax({
                    url: 'http://paper.front.dev/admin/paper/generate',
                    type: 'POST',
                    dataType: 'json',
                    //headers: {}, <-- add headers if needed
                    data : {'name':'John'}
                }).success(function (data) {
                        console.log(data);
                }).error(function(e,s){
                        console.log(e, s);
                }).complete(function(){
                        console.log('ajax request completed');
                });