正直なところ、認証されていないユーザーのすべてのページをブロックするのは良い考えではないと思います。ログインページにどのようにアクセスしますか?
とはいえ、匿名の訪問者がページのホワイトリストにアクセスできるようにするには、アクセスされているページを知っている必要があります。まず、ログインページを含めることをお勧めします。ルートを使用すると、ページを最も簡単に確認できます。したがって、現在一致しているルートをホワイトリストと照合します。ブロックされている場合は、それに基づいて行動します。それ以外の場合は、何もしません。
たとえば、アプリケーションなどのモジュールのModule.php内に例があります。
namespace Application;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\RouteMatch;
class Module
{
protected $whitelist = array('zfcuser/login');
public function onBootstrap($e)
{
$app = $e->getApplication();
$em = $app->getEventManager();
$sm = $app->getServiceManager();
$list = $this->whitelist;
$auth = $sm->get('zfcuser_auth_service');
$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' => 'zfcuser/login'
));
$response = $e->getResponse();
$response->getHeaders()->addHeaderLine('Location', $url);
$response->setStatusCode(302);
return $response;
}, -100);
}
}