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

Php 如果用户未登录,则ZF2重定向到每个页面上的登录页面,php,zend-framework2,Php,Zend Framework2,有没有一种有效的方法可以做到这一点?我研究过的选项: 检查布局中的会话容器 检查模块onBootstrap函数()中的会话容器 在每个控制器/操作中分别处理会话容器 理想情况下,我会检查一次,有没有正确的方法 类似于 $session = new Container('username'); if($session->offsetExists('username')) { //check im not already at my login route

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

  • 检查布局中的会话容器
  • 检查模块onBootstrap函数()中的会话容器
  • 在每个控制器/操作中分别处理会话容器
理想情况下,我会检查一次,有没有正确的方法

类似于

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

作为以下URL中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,它们提供所有功能


链接:

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

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

        return parent::onDispatch($e);
}
您还可以在模块的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);
其中$list将包含未处理的路线列表:

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