Search code examples
phpzend-framework2

Redirect to a route after user login


I know I can do a redirect to a url after a successful user login:

return $this->redirect()->toUrl('/user/login?redirect=http://www.myurl.com');

Now, I'd like to do the same thing to a registered route instead:

'sso-post-login' => array(
    'type' => 'Zend\Mvc\Router\Http\Literal',
    'options' => array(
        'route'    => '/sso-post-login',
        'defaults' => array(
            'controller' => 'Application\Controller\Index',
            'action'     => 'sso-post-login',
        ),
    'may_terminate' => true,
    ),
),

But the following doesn't work:

return $this->redirect()->toUrl('/user/login?redirect=/sso-post-login');

It does not hit my action:

public function ssoPostLoginAction() {
    error_log("In sso post login action");
    $originUrl = Common::getCookie('sso_post_login', $this->getRequest());
    $sessionCookie = Common::getCookie('PHPSESSID', $this->getRequest());
    if (null != $sessionCookie && null != $this->getUserService()->getAuthService()->getIdentity()) {
        $email = $this->getUserService()->getAuthService()->getIdentity()->getEmail();
        $jwtCredentials = $this->buildJWTLoginToken($email);
        $originUrl .= "?jwt=" . $jwtCredentials;
        return $this->redirect()->toUrl($originUrl);
    }
}

It simply redirects to the main page after the login is done.


Solution

  • Is there specific reason you don't want to put full (absolute) url to redirect param? You could do:

    return $this->redirect()->toUrl("/user/login?redirect=".$this->url()->fromRoute('sso-post-login', [], ['force_canonical' => true]));
    

    force_canonical option will generate full url (including your hostname)