老实说,我认为阻止未经身份验证的用户访问每个页面并不是一个好主意。您将如何访问登录页面?
也就是说,您必须知道正在访问的页面,才能将匿名访问者可以访问的页面列入白名单。首先,我建议包含登录页面。您可以使用他们的路线最简单地检查页面。因此,根据白名单检查当前匹配的路由。如果被阻止,请采取行动。否则,什么也不做。
一个示例将在模块的 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);
}
}