CakePHP 4,使用 Auth 插件和范围验证管理面板

CakePHP 4, authenticating admin panel with Auth Plugin and scopes

我在 CakePHP 4 中为我的 Web 应用程序创建了一个带前缀的管理部分。在 config/routes.php 中,我将 Auth 插件限定为这样(因此只有 /admin/* 需要登录:

$routes->prefix('Admin', function (RouteBuilder $routes) {

$routes->registerMiddleware(
    'auth',
    new \Authentication\Middleware\AuthenticationMiddleware($this)
);
$routes->applyMiddleware('auth');
// etc. 

因为我想为面板创建一个简单的登录页面(例如 localhost/admin),所以我在 /Admin/ 文件夹中创建了一个 AdminController.php,并且我尝试连接 '/admin' 到此控制器,这样 URL 就不会显得笨拙 localhost/admin/admin - 但我遇到了验证错误。

$routes->connect(
    '/admin',
    ['prefix' => 'Admin', 'controller' => 'Admin', 'action' => 'index']
 );

这会产生错误: 请求对象不包含所需的身份验证属性

我试图通过再次确定中间件的范围来改善这个问题

$routes->scope('/admin', function(RouteBuilder $routes)
{
    $routes->registerMiddleware(
        'auth',
        new \Authentication\Middleware\AuthenticationMiddleware($this)
    );
    $routes->applyMiddleware('auth');
});

但这不起作用,它给出了同样的错误。

不要在前缀之外创建额外的路由,您可以使用 / 作为将路由连接到当前 prefix/scope 路径的路径:

$routes->prefix('Admin', function (RouteBuilder $routes) {
    $routes->registerMiddleware(
        'auth',
        new \Authentication\Middleware\AuthenticationMiddleware($this)
    );
    $routes->applyMiddleware('auth');
    
    // this will connect `/admin`
    $routes->connect('/', ['controller' => 'Admin', 'action' => 'index']);

    // ...
}

另见