您好我尝试为休息客户端(使用登录身份验证)设置cakephp for ionic(angular)app .
好吧,我配置CakePhp像this setup tutorial,例如我得到的数据:
public function projects()
{
$projects = $this->Projects->find('all');
$this->set([
'projects' => $projects,
'_serialize' => ['projects']
]);
}
并通过Ionic中的 $.http
获取数据
这工作完美但我尝试为移动客户端配置cake auth .
我不知道我是怎么做到的 . 在我的Resttest控制器中,我编写了代码,其中为离子应用程序设置会话ID,但离子不缓存此会话,我认为是我的cakePhp代码是错误的 .
CakePHP控制器:
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Controller\Component\RequestHandlerComponent;
// use Cake\View\Helper\SessionHelper;
class ResttestController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadModel('Projects');
$this->loadModel('Task');
$this->loadModel('User');
$this->viewBuilder()->layout(false);
$this->response->header('Access-Control-Allow-Origin', '*');
$this->loadComponent('Auth', [
'loginAction' => [
'controller' => $this->name,
'action' => 'login',
// '_ext'=>'json'
],
'authorize'=>['Controller'],
]);
// Basic setup
$this->Auth->config('authorize', ['Controller']);
}
public function login(){
header('Access-Control-Allow-Headers: Content-Type, x-xsrf-token');
$this->response->header('Access-Control-Allow-Methods', '*');
if($this->request->is('post')){
$postdata = file_get_contents("php://input");
$d = json_decode($postdata);
if($this->Auth->user()){
$response =array("success"=>2,'msg'=>'logged After');
}
// $d = $this->request->data;
if(!$d->password || !$d->login){
$response = array("success"=>0,'msg'=>'n');
}
$u = $this->User->find()
->where(['email'=>$d->login])
->first();
if($u){
$salt = $u->salt;
$input_password = crypt($d->password, '$2y$12$' . $salt);
$password = $u->password;
if($password == $input_password){
$tok = self::getToken();
$u->token = $tok;
$out = $this->Auth->setUser($u);
$response = array("success"=>1,'msg'=>'logged', 'token'=>$tok, 'out'=>$out,'sadga'=>$this->Auth->identify,'asf'=>$this->Auth,'adsafsfq'=>$d,'$this->request'=>$this->request,'$this->response'=>$this->response,'apache_request_headers '=>apache_request_headers());
}else{
$response = array("success"=>0,'msg'=>'n');
}
}else{
$response = array("success"=>0,'msg'=>'n');
}
}else{
$response =array("success"=>0,'msg'=>'n');
}
$this->set([
'response' => $response,
'_serialize' => ['response']
]);
}
private function getToken(){
return crypt(sha1(md5(uniqid(rand(), true))));
}
public function testAuth(){
}
}
这段代码返回会话和用户数据但不起作用,我认为这不是移动身份验证的好方法 . 你对cakephp的auth有什么想法吗?我如何使我的代码更安全?
1 回答
当我们将应用程序拆分为后端api和前端时,我们应该将后端视为无状态应用程序 . 这意味着你不能使用session for auth .
相反,您应该实现auth / login和auth / register rest endpoints ,它们将返回一些令牌,例如JWT .
对于cakephp2,您可以轻松找到这样的库:https://github.com/t73biz/cakephp2-jwt-auth
配置Auth组件时,请使用此身份验证器而不是Form . 从插件中描述的前端侧传递令牌 .