我正在一个新的CakePHP 4应用程序中实现身份验证(根据CMS教程)
我不得不将Application.php中的getAuthenticationService
方法更改为:
'unauthenticatedRedirect' => \Cake\Routing\Router::url('/users/login'),
和
'loginUrl' => \Cake\Routing\Router::url('/users/login'),
遵循我在here中看到的建议。
这行得通,我得到了登录模板,可以登录,并且正确设置了Auth会话数据。
但是,登录后,我没有重定向到引荐页面,而是重定向到包含我的基本应用程序名称两次的URL:http://localhost/my_app_name/my_app_name/my_controller
因此,我不确定在成功登录后应该在何处设置(或重新设置)基本URL,以进行正确的重定向。
答案 0 :(得分:1)
您遵循the example from the documentation吗? CakePHP已经为您解决了此问题时,请避免使用自定义实现。待会儿你会谢谢你的。
这应该可以正常工作,因为它已经在另一个项目中进行了测试。在此示例中,UsersController具有登录页面。
在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还需要正确的设置初始化函数:
在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已过时,将被授权和身份验证插件取代)。
在您的Application.php中
// In src/Application.php add the following imports
use Authentication\AuthenticationService;
use Authentication\AuthenticationServiceInterface;
use Authentication\AuthenticationServiceProviderInterface;
use Authentication\Middleware\AuthenticationMiddleware;
use Psr\Http\Message\ServerRequestInterface;
答案 1 :(得分:0)
我能够解决这些问题。
它被作为问题here进行了讨论,所以我遵循了。
之后,在我的UsersController.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。
现在登录将按预期方式重定向工作。
答案 2 :(得分:0)
我遵循了 tutorial,只是我更改了 routes.php 文件,以便 / 路由转到用户控制器和登录操作。
$builder->connect('/', ['controller' => 'Users', 'action' => 'login']);