【问题标题】:CakePHP Authentication Middleware not called未调用 CakePHP 身份验证中间件
【发布时间】:2019-12-24 13:29:12
【问题描述】:

我经常使用 AuthComponent,但对 AuthenticationMiddleware 很陌生。我几乎完全遵循https://book.cakephp.org/authentication/2/en/index.html,除了用户名字段是用户名而不是电子邮件。但是当我尝试获取需要身份验证的页面时,Cake 会在 AuthenticationComponent::doIdentityCheck() 中抛出 UnauthenticatedException。这可以理解,因为 Cake 应该将我重定向到 /users/login,但它没有。我试过了

$service->loadAuthenticator('Authentication.Form', [
   'loginUrl' => '/users/login' // case 1
   // or case 2 'loginUrl' => \Cake\Routing\Router::url('/users/login'),
   // or case 3 omit this to use the default

在上述所有情况下,Cakes 都会抛出带有以下消息的 UnauthenticatedException:

未找到身份。您可以通过将 requireIdentity 配置为 false 来跳过此检查。

另外http://localhost:8765/users/login 引导我到正确的页面,如果我允许未经身份验证,我也可以通过http://localhost:8765/users/ 看到用户列表:

// UsersController.php
public function initialize() : void {
    parent::initialize();
    $this->Authentication->allowUnauthenticated(['index', 'login']);
}

我的环境:CakePHP 4.0,身份验证插件 2.0。有没有办法验证 AuthenticationMiddleware 确实已设置并添加到中间件队列中?

【问题讨论】:

    标签: cakephp cakephp-3.x cakephp-4.x


    【解决方案1】:

    如果中间件没有运行,你会得到一个不同的错误,它会抱怨请求对象上缺少 authentication 属性。

    您需要在服务对象上配置unauthenticatedRedirect 选项,以便为未经身份验证的请求发出重定向,如果不配置该选项,您将收到异常。此外,如果您希望在成功登录后能够重定向用户,您可能需要设置 queryParam 选项(即保存最初访问的 URL 的查询字符串参数)。

    $service->setConfig([
        'unauthenticatedRedirect' => '/users/login',
        'queryParam' => 'redirect',
    ]);
    

    文档中似乎缺少这点,只有mentioned in the migration notes。您可能想为 over at GitHub 打开一个问题。 快速入门指南示例已更新为包含重定向配置。

    【讨论】:

      猜你喜欢
      • 2013-11-19
      • 1970-01-01
      • 1970-01-01
      • 2017-06-14
      • 2011-03-11
      • 2011-07-31
      • 2021-07-05
      • 2014-05-11
      • 1970-01-01
      相关资源
      最近更新 更多