如果您想为整个模块设置 HTTP 身份验证,请执行以下操作(至少我是如何做到的):
在 Module.php 中:
public function onBootstrap(MvcEvent $e){
$sharedEvents=$e->getApplication()->getEventManager()->getSharedManager();
$sharedEvents->attach(__NAMESPACE__,MvcEvent::EVENT_DISPATCH, array($this, 'authHttp'));
}
public function authHttp(MvcEvent $e){
$serviceManager = $e->getApplication()->getServiceManager();
$request=$e->getRequest();
$response=$e->getResponse();
if(!(
$request instanceof \Zend\Http\Request
&& $response instanceof \Zend\Http\Response
)){
return; // we're not in HTTP context - CLI application?
}
// Your adapter with config/password etc...
$authAdapter=$serviceManager->get('Admin\AuthenticationAdapter');
$authAdapter->setRequest($request);
$authAdapter->setResponse($response);
$result=$authAdapter->authenticate();
if($result->isValid()){
return true; // everything OK
}
$response->setContent('Access denied');
$response->setStatusCode(\Zend\Http\Response::STATUS_CODE_401);
$e->setResult($response); // short-circuit to application end
return false;
}
就这样 :)。这适用于模块的任何页面!