2

我使用 CakePHP 作为后端,使用 AngularJS 作为前端,而前端和后端位于不同的域中,所以这基本上是一种 CORS 情况。

基本上我正在尝试通过$http.post. 所以这里是代码:

aeapBackend.login = function(username, password) {
    return $http.post(
        API_URL + 'api_mobile_user/login', {
            test: username,
            test2: password
        }
    );
};

而 CakePHP 中对应的 API 如下所示:

function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow(array('login'));
}

public function login() {
    $this->response->header(array(
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Headers' => 'Content-Type'
        )
    );

    $this->autoRender = false;
}

接下来发生的是预检 OPTIONS 请求已完成 - 这对我来说看起来相当不错:

请求标头:

OPTIONS /api_mobile_user/login HTTP/1.1
Host: aeap.localhost
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://asf.localhost
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; en-us) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53
Access-Control-Request-Headers: accept, content-type
Accept: */*
Referer: http://asf.localhost/?username_input=hjk&password_input=hjgk&login_button=
Accept-Encoding: gzip,deflate,sdch
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4

响应标头:

HTTP/1.1 200 OK
Date: Wed, 05 Nov 2014 15:29:00 GMT
Server: Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.5.15
X-Powered-By: PHP/5.5.15
Set-Cookie: CAKEPHP=j6st0hnq8ear2cc6psg56d6eu3; expires=Wed, 05-Nov-2014 19:29:00 GMT; Max-Age=14400; path=/; HttpOnly
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Content-Length: 0
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8

但是当实际的 POST 请求完成时,我得到一个状态码 403:

XMLHttpRequest cannot load http://aeap.localhost/api_mobile_user/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://asf.localhost' is therefore not allowed access. The response had HTTP status code 403. 

我怎样才能避免这种情况?在我看来,我已经为 Cake ['Access-Control-Allow-Origin'] 启用了 CORS 支持。在我看来,AngularJS 发布了一些额外的信息,这些信息在预检期间没有被检查,然后被后端拒绝。

使用的版本:CakePHP 2.5.3,AngularJS:1.3.0

4

2 回答 2

2

感谢 Marvin Smit,我能够确定与 CORS 无关的行为的原因是标题。我设置'Access-Control-Allow-Origin' => '*'在网络服务器级别,所以我能够得到指向 CakePHP 安全组件的响应。

我基本上试图将 POST-Reuqest 发送到一个 API,它不希望数据应该被发布到它。因此访问被拒绝。所以我不得不添加$this->Security->csrfCheck = false到 beforeFilter:

function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow(array('login'));
    $this->Security->csrfCheck = false;
}
于 2014-11-05T16:25:01.543 回答
0

对于它的价值,为 Cakephp 3 执行此操作的正确方法如下

public function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow(array('login'));
    $this->eventManager()->off($this->Csrf);
}

虽然,这不推荐用于 AJAX 请求。以下文档可以为您提供更多帮助。CSRF 和 AJAX

于 2015-11-06T18:01:12.433 回答