如何使用 Cakephp 3 对 json 请求使用基本身份验证并为 html 请求使用表单身份验证?

How to use basic authentication for json requests and form authentication for html requests with 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 请求,因为它具有授权会话。我努力寻找导致这种情况的原因,最终发现您必须明确声明基本身份验证方法的存储介质为 'Memory'。我会在下面的回答中 post 正确的代码。

这个问题类似于 cakephp 2 的这个问题:CakePHP form authentication for normal requests with basic authentication for JSON

您必须明确声明基本身份验证使用内存作为存储介质,否则它会创建一个会话。这是正确的代码:

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'
            ]
        ]);
    }