如何在默认响应护照中添加状态
How to add status in default response passport
我正在Web 和App 中进行开发和应用。对于应用程序 API,我在 laravel 中使用了 Passport。使用护照我可以创建令牌并使用该令牌我验证用户的其他 api 访问权限。但是,如果令牌无效,则它 return 错误消息 "Unauthorized" 没有任何状态。如果我想添加错误状态,如 401 和消息 "Unauthorized",谁能告诉我该怎么做。我必须更改代码的地方,以便我的网络代码不受影响。我想要 json 响应,如下所示,在 json.
中有 2 个字段
状态:401
message:Unauthorized
您可以处理 api 异常并在 app/Exceptions/Handler.php
中格式化其响应。
这是您可以关注的 link
您可以创建一个新的异常处理程序中间件来捕获这些请求并修改它的响应returns。
示例:
class oAuthExceptionHandler {
public function handle($request, Closure $next) {
try {
$response = $next($request);
if (isset($response->exception) && $response->exception) {
throw $response->exception;
}
return $response;
} catch (\Exception $e) {
return response()->json(array(
'result' => 0,
'msg' => $e->getMessage(),
), 401);
}
}
}
然后,在您的 app/Http/Kernel.php
中,命名您的中间件并将其添加到您的 api 组中:
protected $routeMiddleware = [
'oauth_exception' => oAuthExceptionHandler::class,
...
];
protected $middlewareGroups = [
...
'api' => [
'oauth_exception',
...
],
];
我正在Web 和App 中进行开发和应用。对于应用程序 API,我在 laravel 中使用了 Passport。使用护照我可以创建令牌并使用该令牌我验证用户的其他 api 访问权限。但是,如果令牌无效,则它 return 错误消息 "Unauthorized" 没有任何状态。如果我想添加错误状态,如 401 和消息 "Unauthorized",谁能告诉我该怎么做。我必须更改代码的地方,以便我的网络代码不受影响。我想要 json 响应,如下所示,在 json.
中有 2 个字段状态:401 message:Unauthorized
您可以处理 api 异常并在 app/Exceptions/Handler.php
中格式化其响应。
这是您可以关注的 link
您可以创建一个新的异常处理程序中间件来捕获这些请求并修改它的响应returns。
示例:
class oAuthExceptionHandler {
public function handle($request, Closure $next) {
try {
$response = $next($request);
if (isset($response->exception) && $response->exception) {
throw $response->exception;
}
return $response;
} catch (\Exception $e) {
return response()->json(array(
'result' => 0,
'msg' => $e->getMessage(),
), 401);
}
}
}
然后,在您的 app/Http/Kernel.php
中,命名您的中间件并将其添加到您的 api 组中:
protected $routeMiddleware = [
'oauth_exception' => oAuthExceptionHandler::class,
...
];
protected $middlewareGroups = [
...
'api' => [
'oauth_exception',
...
],
];