Authentication cakephp 3.8.13添加admad/cakephp jwt auth

Authentication cakephp 3.8.13添加admad/cakephp jwt auth,authentication,jwt,cakephp-3.0,cakephp-3.8,Authentication,Jwt,Cakephp 3.0,Cakephp 3.8,这个问题在堆栈溢出中被问了很多次,但我尝试了所有公认的解决方案 我是cake PHP的新手,我被指派在我们的应用程序中添加JWT。以前团队使用默认的蛋糕会话。为了集成,我使用了admad/cakephp-jwt-auth。所以在AppController中 public function initialize() { parent::initialize(); $this->loadComponent('RequestHandler');

这个问题在堆栈溢出中被问了很多次,但我尝试了所有公认的解决方案

我是cake PHP的新手,我被指派在我们的应用程序中添加JWT。以前团队使用默认的蛋糕会话。为了集成,我使用了
admad/cakephp-jwt-auth
。所以在AppController中

public function initialize()
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');
        $this->loadComponent('Recurring');
        $this->loadComponent('Auth', [
                'storage' => 'Memory',
                'authenticate' => [
                    'Form' => [
                        'fields' => [
                            'username' => 'user_name',
                            'password' => 'password',
                        ],
                        'contain' => ['Roles']
                    ],
                    'ADmad/JwtAuth.Jwt' => [
                        'parameter' => 'token',
                        'userModel' => 'CbEmployees',
                        'fields' => [
                            'username' => 'id'
                        ],
                        'queryDatasource' => true
                    ]
                ],
                'unauthorizedRedirect' => false,
                'checkAuthIn' => 'Controller.initialize'
            ]);
}
我必须使用
CbEmployees
,这是我们的用户模型

然后在自定义控制器中,添加登录功能

public function login()
    {
        $user = $this->Auth->identify();
        if (!$user) {
            $data = "Invalid login details";
        } else {
            $tokenId  = base64_encode(32);
            $issuedAt = time();
            $key = Security::salt();
            $data = JWT::encode(
                [
                    'alg' => 'HS256',
                    'id' => $user['id'],
                    'sub' => $user['id'],
                    'iat' => time(),
                    'exp' =>  time() + 86400,
                ],
                $key
            );
        }
        $this->ApiResponse([
            "data" => $data
        ]);
    }
然后我使用带body的postman调用这个函数

{
    "username": "developer",
    "password": "dev2020"
}
我总是得到响应为
无效的登录详细信息
。因此,建议的解决方案是检查密码数据类型和长度。密码是varchar(255)。另一个解决方案是检查实体中的密码。在我拥有的实体中

protected function _setPassword($password)
    {
        if (strlen($password) > 0) {
            return Security::hash($password, 'sha1', true);
            // return (new DefaultPasswordHasher)->hash($password);
        }
    }
我特别问团队为什么使用
Security::hash($password'sha1',true)由于从蛋糕2迁移到蛋糕3,他们必须使用相同的代码


为什么我总是获得无效的登录详细信息?我做错了什么?使用应用程序时,我可以使用相同的凭据登录。

首先,当身份验证器配置为使用
用户名(带下划线)时,您使用的是
username
。另外,它看起来像是在发送JSON数据,因此您必须确保在auth组件使用之前对其进行了正确解码(通常使用、或完成)。还请注意,可以通过,甚至“硬编码”哈希实现向后兼容性,但不建议这样做!谢谢,添加回退和弱散列解决了这个问题。