使用此插件的原因是因为我想要一个简单的方法来处理有关受保护方法的API调用的身份验证,并在将来处理日志记录等.
为了防止重复,插件是按照上一个问题进行设置的:CakePHP REST Plugin not returning data已经被修复和运行了.
下一部分是处理身份验证.我已经将以下内容添加到我的beforeFilter方法中,基本上应该说如果它是一个休息调用,并且用户没有登录(注意:并非所有方法都要求用户登录),然后登录.
if (!$this->Auth->user()) { if ($this->Rest->isActive()) { $loginUser = $this->User->loginUser( $credentials['username'],AuthComponent::password($credentials['password']) ); if($loginUser) { if (!$this->Auth->login($loginUser['User'])) { $msg = sprintf('Unable to log you in with the supplied credentials. '); return $this->Rest->abort(array('status' => '403','error' => $msg)); } } } }
对于那些想要看到模特儿的人来说:
public function loginUser($usernameOrEmail,$password) { return $this->find('first',array( 'conditions' => array( 'OR' => array( 'User.email' => $usernameOrEmail,'User.username' => $usernameOrEmail,'User.phone' => $usernameOrEmail ),'User.password' => $password ),'recursive' => -1 )); }
但是我不能让它上班.我正在做这样的请求进行测试:
$.ajax({ url: 'http://domain.com/users/test.json',dataType: 'jsonp',data: { username: 'test',password: 'test' },headers: { Authorization: "TRUEREST" },success: function(response) { console.log(resonse); },error: function(jqXHR,textStatus,errorThrown) { console.log(jqXHR,errorThrown); } });
我在这里的三个主要问题是:
>我在这里手动传递用户名和密码BUT是标题部分是否正确?关于这一点的解释对于这里的文档来说是相当模糊的:https://github.com/kvz/cakephp-rest-plugin#authorization
是$凭证[‘用户名’]去拿起它吗? $凭证是HTTP身份验证的全球事情还是我错过了什么?
>这是每次他们提出请求时都记录用户?如果是这样,似乎有点乱七八糟.
当前的代码实现错误与:未捕获SyntaxError:意外的令牌:
这里是JSON输出,对我来说看起来不错
{ "data": { "User": [] },"Meta": { "status": "error","Feedback": [{ "message": "Log in to continue","level": "error" }],"request": { "http_host": "domain.com","http_user_agent": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit\/537.22 (KHTML,like Gecko) Chrome\/25.0.1364.29 Safari\/537.22","server_addr": "##.##.###.###","remote_addr": "##.###.###.###","server_protocol": "HTTP\/1.1","request_method": "GET","request_uri": "\/users\/test.json?callback=jQuery172015279368730261922_1358207116601&username=test&password=test123&_=1358207116611","request_time": 1358207116 },"credentials": { "class": null,"apikey": null,"username": null },"time_epoch": "1358207117","time_local": "Mon,14 Jan 2013 15:45:17 -0800","version": "0.3" } }
解决方法
缺少凭据
我没有看到你设置$credentials变量在任何地方. .ajax中的数据选项作为GET请求传递.您可能需要从$credentials [‘var’]更新为$_GET [‘var’].如果我记得正确,这些也可以在$this-> data-> params [‘username’]和$this-> data-> params [‘password’]中找到.
如果用户不是Auth’d怎么办?
我看到你的if(!$this-> Auth-> user()),并且我看到你试图拉出用户信息的位置,但逻辑似乎会允许一个未经授权的用户通过.你可能想再看一下这个逻辑.这是我会做的:
if ($this->Rest->isActive()) { $user = $this->User->loginUser( $_GET['username'],AuthComponent::password($_GET['password']) ); if (!$this->Auth->login($user)) { $msg = sprintf('Unable to log you in with the supplied credentials. '); return $this->Rest->abort(array('status' => '403','error' => $msg)); } } else { // handle the non-rest request }