如何在Laravel Passport中处理OAuth异常?

时间:2019-06-25 09:19:38

标签: laravel exception oauth laravel-passport

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

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

sequ

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

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());
        }
    }

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

2 个答案:

答案 0 :(得分: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');

    }
}

答案 1 :(得分:0)

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

例如,您可以使用:

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