diff --git a/docs/en/index.rst b/docs/en/index.rst index dd65787c..e269e05e 100644 --- a/docs/en/index.rst +++ b/docs/en/index.rst @@ -85,12 +85,12 @@ define the ``AuthenticationService`` it wants to use. Add the following method t // Define where users should be redirected to when they are not authenticated $service->setConfig([ - 'unauthenticatedRedirect' => Router::url([ + 'unauthenticatedRedirect' => [ 'prefix' => false, - 'plugin' => null, + 'plugin' => false, 'controller' => 'Users', 'action' => 'login', - ]), + ], 'queryParam' => 'redirect', ]); diff --git a/src/AuthenticationService.php b/src/AuthenticationService.php index da88ee40..69d0b1d3 100644 --- a/src/AuthenticationService.php +++ b/src/AuthenticationService.php @@ -26,6 +26,7 @@ use Authentication\Identifier\IdentifierCollection; use Authentication\Identifier\IdentifierInterface; use Cake\Core\InstanceConfigTrait; +use Cake\Routing\Router; use InvalidArgumentException; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; @@ -372,6 +373,9 @@ public function getUnauthenticatedRedirectUrl(ServerRequestInterface $request): if ($target === null) { return null; } + if (is_array($target) && class_exists(Router::class)) { + $target = Router::url($target); + } if ($param === null) { return $target; } diff --git a/tests/TestCase/AuthenticationServiceTest.php b/tests/TestCase/AuthenticationServiceTest.php index 4fa45df7..8d062952 100644 --- a/tests/TestCase/AuthenticationServiceTest.php +++ b/tests/TestCase/AuthenticationServiceTest.php @@ -32,6 +32,7 @@ use Cake\Http\ServerRequest; use Cake\Http\ServerRequestFactory; use Cake\I18n\DateTime; +use Cake\Routing\Router; use InvalidArgumentException; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; @@ -818,6 +819,30 @@ public function testGetUnauthenticatedRedirectUrl() ); } + public function testGetUnauthenticatedRedirectUrlAsArray() + { + Router::fullBaseUrl('http://localhost'); + + $builder = Router::createRouteBuilder('/'); + $builder->connect( + '/login', + ['controller' => 'Users', 'action' => 'login'], + ['_name' => 'login'], + ); + + $service = new AuthenticationService(); + $request = ServerRequestFactory::fromGlobals( + ['REQUEST_URI' => '/secrets'], + ); + $service->setConfig('unauthenticatedRedirect', [ + 'prefix' => false, + 'plugin' => false, + 'controller' => 'Users', + 'action' => 'login', + ]); + $this->assertSame('/login', $service->getUnauthenticatedRedirectUrl($request)); + } + public function testGetUnauthenticatedRedirectUrlWithBasePath() { $request = ServerRequestFactory::fromGlobals(