简体   繁体   English

REST API上的CakePHP身份验证

[英]CakePHP Authentication on REST API

So I'm creating a REST API for a web app I'm developing, and I know the basic ways for authentication are either sending the credentials on each request or sending a token. 所以我正在为我正在开发的Web应用程序创建一个REST API,我知道身份验证的基本方法是在每个请求上发送凭据或发送令牌。

Since I have never used token before, I think I may send the credentials for each request. 由于我以前从未使用过令牌,我想我可以为每个请求发送凭据。 The point is I can't find any examples on how to handle this in the controller. 关键是我找不到任何关于如何在控制器中处理这个问题的例子。 Would it be something like this? 它会是这样的吗?

public function api_index() {
    if(!$this->Auth->login()) return;

    $this->set(array(
        'models' => $this->Model->find('all'),
        '_serialize' => array('models')
    ));
}

I don't really think this is the way AuthComponent::login() works, can I get some directions here please? 我真的不认为这是AuthComponent::login()工作方式,我可以在这里得到一些指示吗?

Alright, first a clarification about how AuthComponent::login works. 好的,首先澄清一下AuthComponent :: login的工作原理。 In Cake 2.x that method does not do any authentication, but rather creates the Auth.User array in your session. 在Cake 2.x中,该方法不进行任何身份验证,而是在会话中创建Auth.User数组。 You need to implement the actual authentication yourself (the User model is a natural place to do this). 您需要自己实现实际的身份验证(用户模型是一个自然的地方)。 A basic authentication method might look like this: 基本身份验证方法可能如下所示:

App::uses('AuthComponent', 'Controller/Component');
public function authenticate($data) {
    $user = $this->find('first', array(
        'conditions' => array('User.login' => $data['login']),
    ));
    if($user['User']['password'] !== AuthComponent::password($data['password']) {
        return false;
    }

    unset($user['User']['password']);  // don't forget this part
    return $user;
    // the reason I return the user is so I can pass it to Authcomponent::login if desired
}

Now you can use this from any controller as long as the User model is loaded. 现在,只要加载了用户模型,就可以从任何控制器使用它。 You may be aware that you can load it by calling Controller::loadModel('User') . 您可能知道可以通过调用Controller::loadModel('User')来加载它。

If you want to authenticate every request, then you should then put in the beforeFilter method of AppController: 如果你想验证每个请求,那么你应该放入AppController的beforeFilter方法:

public function beforeFilter() {
    $this->loadModel('User');
    if(!$this->User->authenticate($this->request->data)) {
        throw new UnauthorizedException(__('You don\'t belong here.'));
    }
}

All of the above assumes that you pass POST values for login and password every time. 以上所有假设您每次都会传递登录名和密码的POST值。 I think token authentication is definitely the better way to go, but for getting up and running this should work. 我认为令牌认证绝对是更好的方法,但是为了起床和运行这应该是有效的。 Some downsides include sending password in cleartext (unless you require ssl) every request and the probably high cpu usage of the hashing algorithm each time. 一些缺点包括以明文形式发送密码(除非您需要ssl)每次请求以及散列算法可能的高CPU使用率。 Nevertheless, I hope this gives you a better idea of how to do authentication with cakephp. 不过,我希望这能让您更好地了解如何使用cakephp进行身份验证。

Let me know if something needs clarifying. 如果有需要澄清,请告诉我。

Update: Since posting this, I found out that you can actually use AuthComponent::login with no parameters, but I am not a fan of doing so. 更新:自发布以来,我发现您实际上可以使用没有参数的AuthComponent :: login,但我不是这样做的粉丝。 From the CakePHP documentation: 从CakePHP文档:

In 2.x $this->Auth->login($this->request->data) will log the user in with 
 whatever data is posted, whereas in 1.3 $this->Auth->login($this->data) 
 would try to identify the user first and only log in when successful.

AuthComponent::login() creates a session variable that stores the user data, so say you had data that was something like. AuthComponent :: login()创建一个存储用户数据的会话变量,所以说你有类似的数据。

$data = array('User' => array('id' => 1, 'username' => 'johndoe'));

Then you would use 然后你会用

$this->Auth->login($data);

And access the data with 并使用。访问数据

$this->Auth->user('User');

To get the user id 获取用户ID

$this->Auth->user('User.id');

In your AppControllers beforefilter put $this->Auth->deny(); 在你的AppControllers beforefilter中放入$this->Auth->deny(); that will deny all actions to someone who is not logged in. Then in each controllers before filter you want to $this->Auth->allow(array('view')); 这将拒绝所有未登录的人的操作。然后在每个控制器中过滤之前你想要$this->Auth->allow(array('view')); 'view' being the name of an action you want to be public. 'view'是您想要公开的动作的名称。

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

Cakephp 2.X , After lots of research about this on internet I did not find any satisfactory answer So I found a way myself to do this. Cakephp 2.X ,经过对互联网的大量研究后,我没有找到任何满意的答案所以我找到了一种方法来做到这一点。 May be this answer will help some folks in future. 可能这个答案将来会帮助一些人。 This answer is only applicable for REST API's in cake php. 这个答案仅适用于蛋糕php中的REST API。

Add following line in your logic action of REST API before checking for the $this->Auth->login(). 在检查$this->Auth->login().之前,在REST API的逻辑操作中添加以下行$this->Auth->login().

 $this->request->data['User'] = $this->request->data ; 
 if($this->Auth->login()){
    echo "Hurray You are logged In from REST API.";
 }
 else
 {
    throw new UnauthorizedException(__('You don\'t belong here.'));
 }

Desciption : As @threeve said in one of the answers that $this->Auth->login() does not do any authentication itself. Desciption :正如@threeve在其中一个答案中所说的那样, $this->Auth->login()本身不进行任何身份验证。 but rather creates the Auth.User array in your session. 而是在会话中创建Auth.User数组。 For Authentication we require our $this->request->data to be inside User array since User is the model which will check the Credentials in Database. 对于身份验证,我们要求$ this-> request-> data在User数组中,因为User是将检查数据库中的凭据的模型。 Therefore we have to pass the data to Auth as it is required when not using REST API's. 因此,当不使用REST API时,我们必须将数据传递给Auth。 Rest of the things will be handled by Cake and Auth itself. 其余的事情将由Cake和Auth本身处理。

Any enhancements or suggestions on this answer are most welcome. 对此答案的任何改进或建议都是最受欢迎的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM