Laravel passport API将异常作为HTML而不是JSON响应返回

时间:2017-08-16 13:39:54

标签: laravel laravel-passport

我的API是使用Laravel 5.4 Passport构建的,授权和发布访问令牌工作正常,但在使用Insomnia或Postman处理如下资源时:

Authorization: Bearer [encrypted access token goes here which has only "manage-users" scope]
Content-Type: application/json
Accept: application/json

我将上述请求发送到此网址:

  

http://apiendpoint.loc/api/users

已限制访问具有此范围的令牌的这种追索权

  

manage-users,test-scope-1

Route::get('/users', [
    'as' => 'users', 
    'uses' => 'UsersController@index'
])->middleware(['auth:api', 'scopes:manage-users,test-scope-1']);

范围已在:

中定义
  

AuthServiceProvider

Passport::tokensCan([
    'manage-users' => 'testing',
    'test-scope-1' => 'test scope',
    'test-scope-2' => 'another test scope',
]);
protected $routeMiddleware = [
    ...,
    ...,
    ...,
    'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
    'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class        
];

用于授权此请求的令牌仅具有“管理用户”范围,因此除了访问此资源(“test-scope-1”)所需的范围之外,我还希望获得带有未授权访问401的json响应。

虽然我收到了HttpException“提供的无效范围。”作为HTML响应不是json

编辑 Auth-Scaffolding is not installed.

1 个答案:

答案 0 :(得分:0)

经过大量挖掘后,我找到了一种方法来解决早期异常处理程序中的问题,如下所示:

public function render($request, Exception $exception)
{

    // If the request wants JSON (AJAX doesn't always want JSON)
    if ($request->wantsJson()) {

    if($exception instanceof MissingScopeException){
        // Define the response
        $response = [
            'errors' => 'Sorry, something went wrong.'
        ];

        // If the app is in debug mode
        if (config('app.debug')) {
            // Add the exception class name, message and stack trace to response
            //$response['exception'] = get_class($exception); // Reflection might be better here
            $response['message'] = $exception->getMessage();
            //$response['trace'] = $exception->getTrace();
        }

        // Default response of 401
        $status = 403;//forbidden

        // If this exception is an instance of HttpException
        if ($this->isHttpException($exception)) {
            // Grab the HTTP status code from the Exception
            $status = $exception->getStatusCode();
        }

        // Return a JSON response with the response array and status code
        return response()->json($response, $status);
    }

    }
    return parent::render($request, $exception);
}

所以我能够及早捕获错误并返回一个json对象作为响应。