基于Basic类型的API认证:CakePHP插件实现方案
实现CakePHP用户认证(JSON接口版)
安装认证插件
通过Composer安装指定版本的CakePHP认证插件:composer require "cakephp/authentication:^2.0"配置JSON响应格式
生成CRUD后,需将接口响应统一设置为JSON格式,示例代码如下:$this->response ->withType('application/json') ->withStatus(200) ->withStringBody(json_encode($dataOrMessage));用户密码加密处理
在用户实体类中添加密码哈希的setter方法,确保用户注册时密码被加密存储:protected function _setPassword(string $password) : ?string { if (strlen($password) > 0) { return (new DefaultPasswordHasher())->hash($password); } }实现认证服务与登录逻辑
需要在Application类中实现AuthenticationServiceProviderInterface接口以满足插件要求,同时编写登录接口的核心逻辑:public function login() { if ($this->request->is('post')) { $result = $this->Authentication->getResult(); if ($result && $result->isValid()) { return $this->response ->withType('application/json') ->withStatus(200) ->withStringBody(json_encode($result->getData())); } else { return $this->response ->withType('application/json') ->withStatus(401) ->withStringBody(json_encode(['message' => '用户名或密码错误!'])); } } }登出功能可参考CakePHP官方文档中认证插件的对应实现规范。
这是我研究后找到的相对易落地的方案,当然用户认证的实现方式不止这一种。
内容的提问来源于stack exchange,提问作者Yuri Aguiar
相关产品推荐
相关产品推荐

