【发布时间】:2016-04-07 08:11:41
【问题描述】:
我想限制对我的 rest api 的访问,仅使用请求“Accept:”中的属性,值为“application/json or xml”,并且对于每个 rest 调用。在 ZF2 单独的模块中,我可以在哪里以及如何做到这一点,仅适用于 Rest 调用。我的实现类似于这里的指南:enter link description here
【问题讨论】:
标签: php json rest zend-framework2
我想限制对我的 rest api 的访问,仅使用请求“Accept:”中的属性,值为“application/json or xml”,并且对于每个 rest 调用。在 ZF2 单独的模块中,我可以在哪里以及如何做到这一点,仅适用于 Rest 调用。我的实现类似于这里的指南:enter link description here
【问题讨论】:
标签: php json rest zend-framework2
您可以将侦听器连接到onroute 事件,检查Accept 标头值并为除application/json 或application/xml 之外的所有标头返回406 Not Acceptable 响应。
在onBootstrap 连接你的听众:
$eventManager->attach($serviceManager->get('Application\Listener\RestAcceptListener'));
在你的监听器中检查Accept 标头
/**
* Check Accept header
*
* @param MvcEvent $event
* @return Response
*/
public function onRoute(MvcEvent $event)
{
$routeMatch = $event->getRouteMatch();
$controller = $routeMatch->getParam('controller');
// To limit for rest calls only you can do some controller check here
// You can also do instanceof check this is all up to you...
if( $controller !== 'somecontroller'){
return;
}
$request = $event->getRequest();
$headers = $request->getHeaders();
$acceptHeader = $headers->get('Accept');
// Check whether accept type corresponds to the allowed ones
$accept = array('application/json', 'application/xml');
if(!$acceptHeader->match($accept)){
$response = new Response();
$response->setStatusCode(406);
return $response;
}
}
要进行模块检查,您可以使用控制器的命名空间。例如使用 php explode 检查Application 模块:
$parts = explode('\\', $controller, 2);
if ($parts[0] !== 'Application'){
// We do not have a controller from Application module
return;
}
【讨论】: