CakePHP log in redirect to requested URL

主宰稳场 提交于 2019-12-07 14:06:44

问题


When a user clicks a link that requires a log in, we currently redirect them to the log-in page ,but we lose the intended URL. What is the best way to account for that URL and redirect the user to the requested page once logged in?

We're using the latest stable version of Cake. Thanks.

--Edit--

Its configured like this

$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');

login function in 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);
}

When I navigate to an unauthorized page like localhost/mysite/unauthorized I am redirected to localhost/mysite/users/login. In my debug.log file The Redirect Session Key prints out as users/dashboard which implies that there is no valid referrer. To validate that assumption I also print out the referrer in the login function which does in fact return "/" which is the default value in the case of no referrer information from the requester I believe.


回答1:


"According to the cake documentation the authcomponent only preserves this in the session if the user is not coming from an external link."

Read the section again:

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.

It will remember the page you were trying to access, unless you went to the login page directly and hence there's no previous page you came from. If you link to /foo/secret_page and are redirected to the login page though, /foo/secret_page should be remembered in the session.

If you get rid of the $this->Auth->autoRedirect = false and let the AuthComponent do its thing, it should work the way you want.

Otherwise you can read and set the 'Auth.redirect' session key manually to have more control over redirects.



来源:https://stackoverflow.com/questions/3964183/cakephp-log-in-redirect-to-requested-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!