簡體   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