繁体   English   中英

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

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

有一种有效的方法可以做到这一点吗? 我研究过的选项:

  • 检查布局中的会话容器
  • 检查onBootstrap functions()模块中的会话容器
  • 在每个Controller / Action中分别处理会话容器

理想情况下,我会进行一次检查,是否有任何正确的方法?

类似于...

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

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

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

        return parent::onDispatch($e);
}

您还可以在模块的onBootstrap function()上检查会话,您需要使用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);

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

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

作为以下网址中ZFcAuth插件中的签出,我找到了一些用于检查和重定向的代码。

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;
}

此代码块显示了验证/重定向的方法。 但是,它们不是内置方式,因为ZF2仅提供组件。 您还可以使用其他插件,例如ZfcUser,ZfcAcl,ZfcRABC,它们提供所有功能。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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