如何使用基本身份验证的json请求和表单身份验证的html请求与Cakephp 3



我需要过滤json请求并允许对这些请求进行基本身份验证,而只允许对html请求进行表单身份验证。当我在AppController.php中的初始化函数中过滤请求时:

if ($this->request->is('json')) {
        $this->loadComponent('Auth', [
            'authorize' => ['Controller'],
            'authenticate' => [
                'Basic' => [
                    'fields' => ['username' => 'email', 'password' => 'password'],
                    'contain' => ['Districts']
                ]
            ]
        ]);
    } else {
        $this->loadComponent('Auth', [
            'authorize' => ['Controller'],
            'authenticate' => [
                'Form' => [
                    'fields' => ['username' => 'email', 'password' => 'password'],
                    'contain' => ['Districts']
                ]
            ],
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login'
            ],
            'logoutRedirect' => [
                'controller' => 'Users',
                'action' => 'login'
            ]
        ]);
    }

json请求创建并存储一个会话,允许用户访问站点的其余部分,包括html请求,因为它具有授权的会话。我努力寻找导致这种情况的原因,最终发现您必须明确声明基本身份验证方法的存储介质为"内存"。我将在下面的答案中发布正确的代码。

这个问题类似于cakephp 2的这个问题:cakephp表单认证对JSON进行基本认证

您必须显式声明Basic Authentication使用Memory作为存储介质,否则它将创建一个会话。下面是正确的代码:

if ($this->request->is('json')) {
        $this->loadComponent('Auth', [
            'authorize' => ['Controller'],
            'authenticate' => [
                'Basic' => [
                    'fields' => ['username' => 'email', 'password' => 'password'],
                    'contain' => ['Districts']
                ]
            ],
            'storage' => 'Memory'
        ]);
    } else {
        $this->loadComponent('Auth', [
            'authorize' => ['Controller'],
            'authenticate' => [
                'Form' => [
                    'fields' => ['username' => 'email', 'password' => 'password'],
                    'contain' => ['Districts']
                ]
            ],
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login'
            ],
            'logoutRedirect' => [
                'controller' => 'Users',
                'action' => 'login'
            ]
        ]);
    }

最新更新