在自定义组件中,我正在进行API调用。如果API调用返回403,我想注销用户并重定向到登录。使用以下代码,我得到一个响应对象,而不知道响应是否是重定向,或者响应是否包含请求的数据。除了get之外,我还在Component中实现了其他方法,这样我最终可以调用RestAPIComponent超过50次。
调用RestAPIComponent
public function view($id)
{
$resource = $this->__getSingularResourceName();
$$resource = $this->RestApi->get($id)->json;
$this->set(compact($resource));
}
RestAPIComponent
public function get($id = null, array $query = [], $action = null)
{
$path = (is_null($id) === false) ? $id : '';
$response = $this->_http->get($path . '/' . $action, $query, $this->_getAuthHeader());
return $this->_handleResponse($response);
}
private function _handleResponse(Response $response)
{
if ($response->statusCode() == 403) {
$this->Cookie->delete(TOKEN);
$this->Cookie->delete(USER);
$controller = $this->_registry->getController();
return $controller->redirect($controller->Auth->logout());
} else {
return $response;
}
}
答案 0 :(得分:2)
可能有以下原因,使用auth组件获取403错误 - 1.可以获得403通过代码。从CakePHP文档(http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#handling-unauthenticated-requests)中检查出来:如果authenticator返回null,AuthComponent会将用户重定向到登录操作。如果它是一个ajax请求并且指定了AuthComponent :: $ ajaxLogin,则返回该元素,否则返回403 http状态代码。
2.多个Ajax调用不应该是403错误的导致因素。 3.标准路由由CakePHP本身处理。如果您需要一些不同的路由,则应在routes.php中进行配置。我会说使用.htaccess只是为了一个非常极端的路由需求,应该是最后的手段。
4.是的,这可能是一个原因,因为你不再登录,因此得到Auth 403s
有关详细信息,请访问链接Common reasons behind 403 errors