Laravel 5.5 使用 api.token 疑问

升级到5.5后,在日志里发现了大量的报错信息,如下:

[2017-09-12 11:08:20] local.ERROR: The resource owner or authorization server denied the request. {"exception":"[object] (League\\OAuth2\\Server\\Exception\\OAuthServerException(code: 9): The resource owner or authorization 
..... 省略
>handle(Object(Illuminate\\Http\\Request))
#41 {main}

但是api访问均正常返回。于是开始分析。
\vendor\league\oauth2-server\src\AuthorizationValidators\BearerTokenValidator.php(93):
League\OAuth2\Server\Exception\OAuthServerException::accessDenied('The JWT string ...');
throw OAuthServerException::accessDenied($exception->getMessage());

public static function accessDenied($hint = null, $redirectUri = null)
{
    return new static(
        'The resource owner or authorization server denied the request.',
        9,
        'access_denied',
        401,
        $hint,
        $redirectUri
    );
}

很奇怪的是,既然抛出了这个异常,那为什么访问是正常的呢???

我在请求api时候

axios.defaults.headers.common['X-CSRF-TOKEN'] = window._csrf
axios.defaults.headers.common['Authorization'] = `Bearer ${window._token}`
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 7
Aaron

今天跟踪代码,发现了这个问题所在了。应该是你调用了Auth::user()方法,触发了一个token检测流程。
file
这行代码就是检测token,方法里面有异常抛出,

file
这儿捕获到这个异常后,就向框架报告了这个事件。

file
这儿就是调用logger对象,把这个事件写入日志系统。但是这样不影响api请求的,user方法会返回为空null。

6年前 评论
williamQian 3年前

@Aaron 请问下 League\OAuth2\Server\Exception\OAuthServerException 这个异常我可以在 App\Exceptions\Handler 里面的 report 函数里捕获, 但是在 render 里面捕获不了。 因为现在这个异常返回的是状态码 401 然后内容为 Unauthorized. 。因为我想把这个异常按我自己定义的格式输出。

5年前 评论

@tiandaye 已解决,在中间件中。

5年前 评论
zoroo

@tiandaye 我今天也遇到了类似的情况,是 App\\Http\\Middleware\\Authenticate 这个中间件调用 App\\Http\\Middleware\\Authenticate 抛出的异常,但是我在中间件里面捕获这个异常捕获不到

5年前 评论

@tiandaye 请问怎么解决的

5年前 评论

@zrt

我是捕获不到这个异常,因为在这一步就被response

    public function handle($request, Closure $next, $guard = null)
    {
        if ($this->auth->guard($guard)->guest()) {
            return response(['message' => '未授权', 'code' => 401, 'status' => 'error'], 401);
            // return response('Unauthorized.', 401);
        }

        return $next($request);
    }
5年前 评论
Destiny

App\Exceptions\Handler.php 文件中增加以下错误报告忽略项即可解决

  /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        "\League\OAuth2\Server\Exception\OAuthServerException",
    ];
3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!