I would like to limit the access to my rest api only with attribute in the request "Accept:" with value "application/json or xml" and that for every rest call. Where and how i can do that in ZF2 separate module only for Rest calls. my implementation is similar to this guide here: enter link description here
1 Answer
You can connect a listener to onroute event, check the Accept header value and return a 406 Not Acceptable response for all headers other then application/json or application/xml.
In onBootstrap connect your listener:
$eventManager->attach($serviceManager->get('Application\Listener\RestAcceptListener'));
In your listener check the Accept header
/**
* 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;
}
}
UPDATE:
To make a module check you can use namespace of the controller. For example to check Application module using php explode:
$parts = explode('\\', $controller, 2);
if ($parts[0] !== 'Application'){
// We do not have a controller from Application module
return;
}
1 Comment
Emrah Mehmedov
can i limit for some specific module? for example when i'm in Rest module instead application?