always returns status code 200

2019-08-26 12:20发布

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条回答
祖国的老花朵
2楼-- · 2019-08-26 13:17

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'

查看更多
登录 后发表回答