如果用户未登录,则 ZF2 重定向到每个页面上的登录页面

Jac*_*tle 2 php zend-framework2

有没有一种有效的方法来做到这一点?我研究过的选项:

  • 检查布局中的会话容器
  • 检查模块 onBootstrap functions() 中的会话容器
  • 在每个控制器/动作中单独处理会话容器

理想情况下,我会检查一次,有没有正确的方法来做到这一点?

类似的东西...

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

Vip*_*pul 5

您可以在每个控制器中使用以下代码

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

        return parent::onDispatch($e);
}
Run Code Online (Sandbox Code Playgroud)

您还可以在模块的 onBootstrap 函数()上检查会话,您需要使用 zf2 事件匹配路由:

$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);
Run Code Online (Sandbox Code Playgroud)

其中 $list 将包含不处理的路由列表:

$list = array('login', 'login/authenticate');
Run Code Online (Sandbox Code Playgroud)