简体   繁体   中英

ZF2 redirect to login page on every page if user is not logged in

Is there an efficient way to do this? Options I've looked into:

  • Checking the session container in the layout
  • Checking the session container in the module onBootstrap functions()
  • Handling the session container individually in each Controller/Action

Ideally I'd have this check once, is there any correct way to do this?

Something along the lines of...

$session = new Container('username');
    if($session->offsetExists('username')) {
        //check im not already at my login route
        //else redirect to login route
    }
}

You can use below code inside each controller

public function onDispatch(\Zend\Mvc\MvcEvent $e)
{
        if (! $this->authservice->hasIdentity()) {
            return $this->redirect()->toRoute('login');
        }

        return parent::onDispatch($e);
}

You can also check session on module's onBootstrap function(), you need to match the route using zf2 events:

$auth = $sm->get('AuthService');
$em->attach(MvcEvent::EVENT_ROUTE, function ($e) use($list, $auth)
{
    $match = $e->getRouteMatch();

    // No route match, this is a 404
    if (! $match instanceof RouteMatch) {
        return;
    }

    // Route is whitelisted
    $name = $match->getMatchedRouteName();

    if (in_array($name, $list)) {
        return;
    }

    // User is authenticated
    if ($auth->hasIdentity()) {
        return;
    }

    // Redirect to the user login page, as an example
    $router = $e->getRouter();
    $url = $router->assemble(array(), array(
        'name' => 'login'
    ));

    $response = $e->getResponse();
    $response->getHeaders()
        ->addHeaderLine('Location', $url);
    $response->setStatusCode(302);

    return $response;
}, - 100);

where $list will contain the list of routes not to be processed:

$list = array('login', 'login/authenticate');

As checkout in ZFcAuth plugin in following urls, I found some code for check & redirect.

if (!$auth->hasIdentity() && $routeMatch->getMatchedRouteName() != 'user/login') {
    $response = $e->getResponse();
    $response->getHeaders()->addHeaderLine(
        'Location',
        $e->getRouter()->assemble(
            array(),
            array('name' => 'zfcuser/login')
        )
    );
    $response->setStatusCode(302);
    return $response;
}

This code chunk show the way to validate/redirect. However they are not in-build way as ZF2 only provide components. You can also use other plugins like ZfcUser, ZfcAcl, ZfcRABC which provide all functionality.

link : https://github.com/ZF-Commons/ZfcUser/issues/187#issuecomment-12088823 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM