always returns status code 200

偶尔善良 提交于 2019-12-25 02:29:35

问题


I am returning response from onBootStrap() this way..

 $app = $e->getApplication();

           $em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($app) {

              $response = $e->getResponse();
                $response->setStatusCode(403);

                $jsonValue = json_encode(array(
                   'error'   => 12345,
                   'message' => 'You are not authorized for this request',
                ));


                $response->setContent($jsonValue);

                return $response;

        }, PHP_INT_MAX);

But the problem is I am getting status code 200 even if I am passing different ones.

I am running this API from Advanced rest API client.


回答1:


Before: You need to interrupt the normal course of processing a request. See module BjyAuthorize. It generates an error: https://github.com/bjyoungblood/BjyAuthorize/blob/master/src/BjyAuthorize/Guard/Route.php#L69 Here it is processed: https://github.com/bjyoungblood/BjyAuthorize/blob/master/src/BjyAuthorize/View/UnauthorizedStrategy.php#L53

In the onBootstrap method you can add a listener for the event MvcEvent::EVENT_DISPATCH_ERROR. It will check whether the error is an Auth error and the need to set the status code of the response and its contents. Auth code will trigger an event MvcEvent::EVENT_DISPATCH_ERROR and set "event error" $event->setError(static::ERROR)

After: This is not the best question is not the best answer. The best answer would be "use standard modules". Nevertheless , there is such a thing as "the ultimate complexity of the system". A sign that the system has reached the limit of complexity is that users find it easier to write your own code and not use the standard. However, there is an objective and a subjective complexity. Objective - standard modules are not very complex. Nevertheless, they are not documented in the best way . Therefore, I believe that my answer aims to reduce the complexity for you a subjective standard system , in this case - the module BjyAuthorize. You can specify your own strategy as follows: 'unauthorized_strategy' => 'MyModule\Listener\UnauthorizedStrategy'



来源:https://stackoverflow.com/questions/20917970/always-returns-status-code-200

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!