API паспорта Laravel возвращает исключение как HTML вместо ответа JSON

Мой 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

Я отправляю вышеуказанный запрос на этот URL:

http://apiendpoint.loc/api/users

который был ограничен доступ к этому обращению к токенам, которые имеют эту область действия

управлять-пользователями, тест-область-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        
];

Токен, используемый для авторизации этого запроса, имеет только область действия «manage-users», поэтому я ожидал получить ответ json с неавторизованным доступом 401 в дополнение к требуемой области для доступа к этому ресурсу, которая называется «test-scope-1».

хотя я получил HttpException «Предоставлены недопустимые области». как HTML-ответ, а не json

Изменить Auth-Scaffolding is not installed.


person ahmedsaber111    schedule 16.08.2017    source источник


Ответы (1)


После долгих поисков я нашел способ обойти проблему ранее в обработчике исключений, как показано ниже:

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 в качестве ответа.

person ahmedsaber111    schedule 17.08.2017