如何在默认回复护照中添加状态 [英] How to add status in default response passport

查看:58
本文介绍了如何在默认回复护照中添加状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Web和App中的应用程序.对于App的API,我在laravel中使用了Passport.使用护照我可以创建令牌,并使用该令牌可以验证用户是否可以进行其他api访问.但是,如果令牌无效,则它将返回错误消息,如未授权",而没有任何状态.如果我想添加错误状态(如401)并显示消息未经授权",谁能告诉我该怎么办.我必须更改代码的位置,以免影响我的Web代码.我想要像下面这样的json响应,其中包含json中的2个字段.

I am developing and application in web as well as App. For App's API I have use Passport in laravel. Using passport i can create token and using that token I verify user for other api access. But if token in invalid then it return Error message like "Unauthorized" without any status. Can any one tell me what to do if i want to add error status like 401 with message "Unauthorized" . Where I have to change in code so that my web code is not affect. I want json response like below with 2 fields in json.

状态:401 消息:未经授权

status:401 message:Unauthorized

推荐答案

您可以创建一个新的异常处理程序中间件来捕获这些请求并修改其返回的响应.

You could create a new exception handler middleware to catch these requests and modify the response it 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组中:

Then, in your app/Http/Kernel.php, name your middleware and add it into your api group:

protected $routeMiddleware = [
    'oauth_exception' => oAuthExceptionHandler::class,
    ...
];

protected $middlewareGroups = [
    ...

    'api' => [
        'oauth_exception',
        ...
    ],
];

这篇关于如何在默认回复护照中添加状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆