Zend Framework 2 限制 REST API 只接受 application/json 或 application/xml

Zend Framework 2 limit REST API to accept only application/json or application/xml

我想限制对我的 rest api 的访问,仅使用请求中的属性 "Accept:" 和值 "application/json or xml" 以及每个 rest 调用的属性。我在哪里以及如何在 ZF2 单独的模块中仅针对 Rest 调用执行此操作。我的实现类似于此处的指南:enter link description here

您可以将侦听器连接到 onroute 事件,检查 Accept header 值和 return 所有 header 的 406 Not Acceptable 响应]s 除了 application/jsonapplication/xml.

onBootstrap 中连接您的侦听器:

$eventManager->attach($serviceManager->get('Application\Listener\RestAcceptListener'));

在你的监听器中检查 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;
    }
}

更新:

要进行模块检查,您可以使用控制器的命名空间。例如检查 Application 模块使用 php explode:

$parts = explode('\', $controller, 2);
if ($parts[0] !== 'Application'){
    // We do not have a controller from Application module
    return;
}