How to respond in Middleware Slim PHP Framework

有些话、适合烂在心里 提交于 2019-12-03 16:48:58
alexw

You cannot use halt in middleware:

https://stackoverflow.com/a/10201595/2970321

Halt should only be invoked within the context of a route callback.

Instead, you could manually generate a 400 response using PHP's header along with exit:

header("HTTP/1.1 400 Access denied");
exit;

Alternatively,

you could define a new type of Exception:

class AuthException extends Exception {
    public function __construct() {
        $message = 'You must authenticate to access this resource.';
        $code = 400;
    }
}

Catch this in your error route:

$app->error(function (\Exception $e) use ($app) {
    // Example of handling Auth Exceptions
    if ($e instanceof AuthException) {
        $app->response->setStatus($e->getCode());
        $app->response->setBody($e->getMessage());
    }
});

And throw an AuthException when authorization is to be denied:

throw new AuthException();

This is essentially how it is done in Slim-Auth.

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