【问题标题】:Zend Framework 2 limit REST API to accept only application/json or application/xmlZend Framework 2 限制 REST API 只接受 application/json 或 application/xml
【发布时间】: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


    【解决方案1】:

    您可以将侦听器连接到onroute 事件,检查Accept 标头值并为除application/jsonapplication/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;
    }
    

    【讨论】:

    • 我可以限制某些特定的模块吗?例如当我在休息模块而不是应用程序时?
    猜你喜欢
    • 2016-05-30
    • 2021-07-05
    • 2022-08-16
    • 2016-09-06
    • 1970-01-01
    • 2015-09-22
    • 2017-03-26
    • 2021-10-30
    • 2021-06-14
    相关资源
    最近更新 更多