当用户单击需要登录的链接时,我们目前会将他们重定向到登录页面,但我们会丢失预期的 URL。考虑该 URL 并将用户登录后重定向到请求的页面的最佳方法是什么?
我们正在使用最新的稳定版本的 Cake。谢谢。
--编辑--
它的配置是这样的
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
// $this->Auth->autoRedirect = false;
$this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'dashboard');
users_controller中的登录功能
function login() {
Debugger::log("Redirect Session Key:" . $this->Session->read('Auth.redirect'), $level = 7);
$ref = $this->referer();
Debugger::log("referer():" . $ref, $level = 7);
}
当我导航到未经授权的页面(例如 localhost/mysite/unauthorized)时,我会被重定向到 localhost/mysite/users/login。在我的 debug.log 文件中,重定向 session key 打印为用户/仪表板,这意味着没有有效的引用者。为了验证这个假设,我还在登录函数中打印出引荐来源网址,它实际上返回“/”,这是我相信请求者没有引荐来源网址信息的情况下的默认值。
最佳答案
"According to the cake documentation the authcomponent only preserves this in the session if the user is not coming from an external link."
阅读section再次:
The AuthComponent remembers what controller/action pair you were trying to get to before you were asked to authenticate yourself by storing this value in the Session, under the
Auth.redirect
key. However, if this session value is not set (if you're coming to the login page from an external link, for example), then the user will be redirected to the URL specified in loginRedirect.
它会记住您尝试访问的页面,除非您直接进入登录页面,因此没有您来自的上一个页面。如果您链接到 /foo/secret_page
并被重定向到登录页面,则应在 session 中记住 /foo/secret_page
。
如果您摆脱 $this->Auth->autoRedirect = false
并让 AuthComponent 完成其工作,它应该按照您想要的方式工作。
否则,您可以手动读取并设置'Auth.redirect'
session key ,以更好地控制重定向。
关于CakePHP 登录重定向到请求的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3964183/