首页 > 解决方案 > CakePHP 4 CMS 身份验证教程重定向到登录不起作用(忽略子文件夹)

问题描述

我正在尝试根据官方 CMS 教程实施身份验证:https ://book.cakephp.org/4/en/tutorials-and-examples/cms/authentication.html#adding-login

但是这里实现的重定向:

public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
    $authenticationService = new AuthenticationService([
        'unauthenticatedRedirect' => '/users/login',
        'queryParam' => 'redirect',
    ]); 

没有按预期工作。

我的安装位于 example.com/project1/ 之类的子文件夹中,正确的完整 url 将是 example.com/project1/users/login 但是当尝试访问 example.com/project1/ 时,重定向指向 example.com/users/登录。

我也试过改变

$authenticationService = new AuthenticationService([
        'unauthenticatedRedirect' => '/users/login',
        'queryParam' => 'redirect',

$authenticationService = new AuthenticationService([
        'unauthenticatedRedirect' => [controller => 'users', 'action' => index],
        'queryParam' => 'redirect',

但这会导致

parse_url() 期望参数 1 是字符串,给定数组

错误

我必须如何设置重定向或在哪里可以更改 CakePHP 4 中的“BASEURL”?

标签: cakephpcakephp-4.x

解决方案


我发现了问题。

我根据@ndm的链接更改了代码:

$authenticationService = new AuthenticationService([
        'unauthenticatedRedirect' => \Cake\Routing\Router::url('/users/login'),
        'queryParam' => 'redirect',

导致无限重定向,因为我忘记将此函数添加到 UsersController:

public function beforeFilter(\Cake\Event\EventInterface $event)
{
    parent::beforeFilter($event);
    // Configure the login action to not require authentication, preventing
    // the infinite redirect loop issue
    $this->Authentication->addUnauthenticatedActions(['login']);
}

推荐阅读