Cakephp 2.5。 Auth Basic:重定向未授权错误

时间:2014-06-17 15:25:03

标签: cakephp authentication

我有一个API,我使用Auth进行基本身份验证。 只要我使用正确的用户名和密码,一切都很顺利!

现在我去看看如果我尝试使用错误的数据登录会发生什么。

我收到错误消息:

Unauthorized
Error:  The requested address '/api' was not found on this server. 

我能做些什么,我可以返回

$this->response->statusCode(401);

而不是其他什么? 我以为我有其他条件,但那个(见下文)没有被调用... 我不知道为什么......

我的代码看起来像这样:

  var $components = array('Auth' => array(
    'loginAction' => array(
        'controller' => 'api',
        'action' => 'login'
    ),
    'authenticate' => array(
        'Basic' => array(
            'userModel' => 'Appuser'
        )
    )));


public function login() {
$this->autoRender = false;

    if ($this->Auth->login()) {
        $this->Appuser->id = AuthComponent::user('id');

        // save last login
        $this->Appuser->saveField('last_login', date("Y-m-d H:i:s"));
        return $this->response->body(json_encode('Hello :-) You are in!'));
    }else{
        return $this->response->body(json_encode(array('ERROR' => array('file' => basename(__FILE__), 'line' => __LINE__, 'msg'=> 'Login failed!'))));
    }

3 个答案:

答案 0 :(得分:1)

尝试unauthorizedRedirect:

AuthComponent::$unauthorizedRedirect

http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#authcomponent-api

答案 1 :(得分:0)

这不是直接反应,但在我的申请中,我做了类似的事情,希望它可以帮到你:

public $components = array(
    'Session',
    'Auth'=>array(
        'loginRedirect' => array('controller' => 'projets', 'action' => 'index', 'admin'=>true),
        'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'admin'=>false, 'intro'),
        'loginError' => "Les informations d'identification sont incorrectes.",
    )
);

答案 2 :(得分:0)

好的,我发现了:

首先我必须添加到我的API

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

然后我按照本教程: http://chetan4cake.blogspot.de/2012/06/exception-handling-in-cakephp-20.html

在app / Lib / Error / AppExceptionRenderer.php

我添加了

public function notAuth($error) {
        $this->controller->beforeFilter();
        $this->controller->response->send(401);
    }
public function unauthorized($error) {
        $this->notAuth($error);
    }

这样,当我尝试输入错误数据时,我的API的每个函数都出现401错误,当我直接调用登录函数时,我设置了" else" if($ this-> Auth-> login())到$ this-> response-> statusCode(401);

相关问题