【问题标题】:How to handle OAuth exception in Laravel Passport?如何处理 Laravel Passport 中的 OAuth 异常?
【发布时间】:2019-11-07 02:14:46
【问题描述】:

我正在研究 laravel 护照包。当我撤销令牌并访问经过身份验证的端点时,它会引发异常。

日志文件包含“资源所有者或授权服务器拒绝请求”。要处理的是异常,我创建了 OAuth 中间件并在其中放置了异常代码,如此链接中所述: https://www.kingpabel.com/oauth2-exception-custom-error-message/

public function handle($request, Closure $next)
    {
        //return $next($request);
         try {
            $response = $next($request);
            // Was an exception thrown? If so and available catch in our middleware
            if (isset($response->exception) && $response->exception) {
                throw $response->exception;
            }
            return $response;
        } catch (OAuthException $e) {
            $data = [
//                'error' => $e->errorType,
//                'error_description' => $e->getMessage(),
                'error' => 'Custom Error',
                'error_description' => 'Custom Description',
            ];
            return \Response::json($data, $e->httpStatusCode, $e->getHttpHeaders());
        }
    }

我想以 json 格式返回错误,例如:

{
    "error": "Token is invalid!"
}

如果有人在这方面指导我,我将不胜感激。 谢谢,

【问题讨论】:

    标签: laravel exception oauth laravel-passport


    【解决方案1】:

    我设法通过这种方式得到它,在handler.php

    use League\OAuth2\Server\Exception\OAuthServerException;
    use Illuminate\Auth\AuthenticationException;
    ....
    
    public function report(Exception $exception)
        {   
            if ($exception instanceof OAuthServerException || $exception instanceof AuthenticationException) {
    
                if(isset($exception->guards) && isset($exception->guards()[0]) ==='api')
                response()->json('Unauthorized', 401) ;
                else if ($exception instanceof OAuthServerException)
                response()->json('Unauthorized', 401) ;
            }
    
            parent::report($exception);
        }
    
    

    然后为了防止浏览器出现跨源错误,添加了middleware,如下所示 注意:使中间件在生产中安全 kernal.php

    protected $middleware = [
            ....
            \App\Http\Middleware\Cors::class,
        ];
    

    cors.php

    use Closure;
    
    class Cors
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
    
            return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
              ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
              ->header('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With')
              ->header('Access-Control-Allow-Credentials',' true');
    
        }
    }
    
    

    【讨论】:

      【解决方案2】:

      捕获特定异常的一个好方法是在App\Exceptions\Handler 文件的render 方法中添加您的自定义逻辑。

      例如,您可以使用:

      if ( $exception instanceof OAuthException ) {
           return response(['error' => 'Token is invalid!'], 403);
      }
      

      【讨论】:

      • 感谢大家的指导,当我从 handler.php 文件中的不报告数组中删除了 AuthenticationException 时,上述解决方案就起作用了。
      • 在我的情况下,护照异常是 Illuminate\Auth\AuthenticationException 的一个实例
      【解决方案3】:

      现在可以使用 Laravel Passport 8.0+ 处理 OAuth 异常。将 vendor/laravel/passport/src/Http/Middleware/HandleOAuthErrors.php 复制到 app/Http/Middleware/HandleOAuthErrors.php 并在 \App 中注册绑定\Providers\AppServiceProvider::register() 方法:

      $this->app->bind(HandleOAuthErrors::class, function () {
          return new \App\Http\Middleware\HandleOAuthErrors;
      });
      

      【讨论】:

      • vendor/laravel/passport/src/Http/Middleware/HandleOAuthErrors.php 不存在了
      猜你喜欢
      • 2021-03-12
      • 1970-01-01
      • 2023-03-19
      • 2021-04-23
      • 2014-04-22
      • 2013-10-22
      • 2018-06-18
      • 1970-01-01
      相关资源
      最近更新 更多