蛋糕PHP 4身份验证 成功登录后重定向



我正在一个新的CakePHP 4应用程序中实现身份验证(根据CMS教程(

我不得不将应用程序中.phpgetAuthenticationService方法更改为:

'unauthenticatedRedirect' => CakeRoutingRouter::url('/users/login'),

'loginUrl' => CakeRoutingRouter::url('/users/login'),

以下是我在这里看到的建议。

这有效,我得到了我的登录模板,可以登录,并且身份验证会话数据设置正确。

但是,登录后,我不会重定向回引用页面,而是重定向到包含我的基本应用程序名称两次的 URL:http://localhost/my_app_name/my_app_name/my_controller

所以我不确定在成功登录后在哪里设置(或更确切地说是重新设置(基本 url 以进行正确的重定向。

您是否遵循了文档中的示例?避免使用自定义实现,因为 CakePHP 已经为您解决了这个问题。你以后会感谢自己的。

这应该可以正常工作,因为它已经在另一个项目中进行了测试。在此示例中,用户控制器具有登录页面。

In src\Controller\UsersController.php

public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Flash->error(__('Username or password is incorrect'));
}
}
}

另外,请记住,您的AppController还需要正确的设置初始化函数:

In src\Controller\AppController.php

/**
* Initialization hook method.
*
* @return void
*/
public function initialize(): void {
$this->loadComponent('Auth', [
// The login page (as referred to above)
'loginAction' => [
'controller' => 'User',
'action' => 'login'
],
// If no url is provided
'loginRedirect' => [
'controller' => 'SomeController',
'action' => 'SomeAction'
],
// If unauthorized, return them to page they were just on
'unauthorizedRedirect' => $this->referer()
]);
}

编辑:CakePHP似乎也更改了他们的身份验证文档(因为显然AuthComponent已被弃用,将被授权和身份验证插件取代(。

在您的应用程序中.php

// In src/Application.php add the following imports
use AuthenticationAuthenticationService;
use AuthenticationAuthenticationServiceInterface;
use AuthenticationAuthenticationServiceProviderInterface;
use AuthenticationMiddlewareAuthenticationMiddleware;
use PsrHttpMessageServerRequestInterface;

我能够解决这些问题。

这里把它作为一个问题讨论,所以我遵循了它。

在我的用户控制器中.php登录方法,之后

$redirect = $this->request->getQuery('redirect', [
'controller' => 'Pages',
'action' => 'home',
]);

我添加了这个:

if(!is_array($redirect)){
if (strncmp($redirect, '/myapp', 6) === 0) {
$redirect = substr($redirect, 6);
}
}

然后删除双 myapp。

现在登录重定向按预期工作。

我按照教程进行操作,只是我更改了路由.php文件,以便/路由转到用户控制器和登录操作。

$builder->connect('/', ['controller' => 'Users', 'action' => 'login']);

最新更新