Reputation: 1987
I am having an API where I use Auth with Basic authentication. As long as I use the correct username and password, everything goes fine!
Now I went to see what will happen if I try to login with wrong data.
I get the error message:
Unauthorized
Error: The requested address '/api' was not found on this server.
Is there anything I can do, that I can return a
$this->response->statusCode(401);
instead of anything other? I thought I had a else condition, but the one (see below) is not getting called... I don't know why...
my code look like this:
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!'))));
}
Upvotes: 0
Views: 1927
Reputation: 11
Try unauthorizedRedirect :
AuthComponent::$unauthorizedRedirect
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#authcomponent-api
Upvotes: 1
Reputation: 1987
OK, I found it out:
first of all I had to add into my API
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('login');
}
Then I followed this tutorial: http://chetan4cake.blogspot.de/2012/06/exception-handling-in-cakephp-20.html
And in app/Lib/Error/AppExceptionRenderer.php
I added
public function notAuth($error) {
$this->controller->beforeFilter();
$this->controller->response->send(401);
}
public function unauthorized($error) {
$this->notAuth($error);
}
This way I get on every function of my API a 401 error when trying to get in with wrong data and when I call directly the login function I set the "else" of the if($this->Auth->login()) to $this->response->statusCode(401);
Upvotes: 0
Reputation: 1618
This is not a direct response, but in my application I made something like this, hope it can help you :
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.",
)
);
Upvotes: 0