2017-08-16 84 views
0

我的API已建成Laravel 5.4護照,授權和發行的訪問令牌是否工作正常,但與資源處理類似下面用失眠或郵差時:Laravel護照API返回的異常爲HTML而不是JSON響應

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

這已經restric泰德訪問該求助於令牌具有這種作用域

管理用戶,測試範圍-1

Route::get('/users', [ 
    'as' => 'users', 
    'uses' => '[email protected]' 
])->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」作用域,因此除了訪問此資源所需的作用域「test-scope-1」之外,我還希望獲得包含未授權訪問的json響應401 」。

雖然我得到了一個HttpException「提供了無效的作用域」。作爲HTML響應不JSON

編輯 Auth-Scaffolding is not installed.

回答

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對象作爲響應。