Php Zend Framework 2将REST API限制为仅接受application/json或application/xml
我想限制对restapi的访问,仅在请求“Accept:”中使用“application/json或xml”的属性,以及每个rest调用的属性。在ZF2单独模块中,我可以在何处以及如何仅针对Rest调用这样做。我的实现与这里的指南类似:您可以将侦听器连接到Php Zend Framework 2将REST API限制为仅接受application/json或application/xml,php,json,rest,zend-framework2,Php,Json,Rest,Zend Framework2,我想限制对restapi的访问,仅在请求“Accept:”中使用“application/json或xml”的属性,以及每个rest调用的属性。在ZF2单独模块中,我可以在何处以及如何仅针对Rest调用这样做。我的实现与这里的指南类似:您可以将侦听器连接到onroute事件,检查接受头值,并返回除应用程序/json或应用程序/xml之外的所有头的响应 在onBootstrap中连接您的侦听器: $eventManager->attach($serviceManager->get('A
onroute
事件,检查接受
头值,并返回除应用程序/json
或应用程序/xml
之外的所有头的响应
在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检查应用程序
模块:
$parts = explode('\\', $controller, 2);
if ($parts[0] !== 'Application'){
// We do not have a controller from Application module
return;
}
我可以限制某些特定模块吗?例如,当我在Rest模块而不是应用程序中时?