我成功安装了 ZFCUser
。现在我想知道是否有办法全局检查身份验证。
如概述in the wiki有几种方法可以检查身份验证。它们都有效,但我是否必须在每一个 操作中真正使用 check-if 子句?我的所有网站都应该只有在登录后才能访问,否则,您应该被重新路由到登录页面。
有人知道是否有一个中心位置可以放置此逻辑吗?
最佳答案
老实说,我不认为为未经身份验证的用户阻止每个 页面是个好主意。您将如何访问登录页面?
也就是说,您必须知道正在访问的页面,才能将匿名访问者可访问的页面列入白名单。首先,我建议包括登录页面。您可以使用他们的路线最简单地检查页面。所以根据白名单检查当前匹配的路由。如果被阻止,请采取行动。否则,什么也不做。
一个例子是在一个模块的 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);
}
}
关于php - Zend Framework 2 - 使用 ZFCUser 进行身份验证的全局检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14137868/