【问题标题】:How to use basic authentication for json requests and form authentication for html requests with Cakephp 3?如何使用 Cakephp 3 对 json 请求使用基本身份验证和对 html 请求使用表单身份验证?
【发布时间】:2016-09-29 03:03:37
【问题描述】:

我需要过滤 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 form authentication for normal requests with basic authentication for JSON

【问题讨论】:

    标签: json cakephp cakephp-3.0 basic-authentication cakephp-3.x


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-13
      • 1970-01-01
      • 1970-01-01
      • 2013-11-09
      • 2011-08-01
      • 2011-04-04
      • 2017-10-14
      • 1970-01-01
      相关资源
      最近更新 更多