我在登录后尝试重定向到当前页面,使用cakephp 3.4但我得到这样的
localhost页面没有工作,locahost页面重定向过多 倍。尝试清除您的Cookie
之后2秒,它会重定向到主页。请帮帮我。 这是我的代码
在appController.php中
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
],
'scope' => ['userStatus' => '1']
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'unauthorizedRedirect' => $this->referer(),
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login'
]
]);
}
在loginController.php中
function login{
if ( $this->request->is( 'post' ) ) {
if ( $this->Auth->login() )
{
$this->redirect($this->referer());
}
else {
$this->Flash->error(__('Your username or password is incorrect.'));
}
}
}
答案 0 :(得分:1)
看起来你在这里有一些重定向循环。您应该使用AuthComponent::redirectUrl()
。
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'));
}
}
}
请参阅文档中的Redirecting Users After Login。
在记录用户后,您通常希望将其重定向回来 到他们来自哪里。传入URL以将目标设置为用户 应该在登录后重定向到。
如果未传递任何参数,则返回的URL将使用以下内容 规则:
- 如果是,则从重定向查询字符串值返回规范化的URL 存在并且当前应用程序正在运行的同一域中。 在3.4.0之前,使用了
Auth.redirect
会话值。- 如果没有查询字符串/会话值并且存在配置
loginRedirect
,则返回loginRedirect
值。- 如果没有重定向值且没有
loginRedirect
,则会返回/
。
答案 1 :(得分:0)
使用$this->Auth->redirectUrl()
代替$this->referer()
。
在记录用户之后,您通常希望将它们重定向回原来的位置。传入URL以设置用户登录后应重定向到的目的地。
loginRedirect
,则会返回/
。添加到AuthComponent
配置选项:
loginRedirect
控制器操作用户的URL(定义为字符串或数组) 应该在登录后重定向到。此值将被忽略 如果用户在其会话中具有Auth.redirect值。
您的代码应该是这样的:
在appController.php中
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
],
'scope' => ['userStatus' => '1']
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'unauthorizedRedirect' => $this->referer(),
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Pages',
'action' => 'display'
]
]);
}
在loginController.php中
function login{
if ( $this->request->is( 'post' ) ) {
if ( $this->Auth->login() )
{
$this->redirect($this->Auth->redirectUrl());
}
else {
$this->Flash->error(__('Your username or password is incorrect.'));
}
}
}