用户未经授权时,Laravel通行证自定义错误消息和状态代码

时间:2017-12-29 12:18:03

标签: laravel authentication laravel-5 oauth laravel-passport

我的项目正在Laravel 5.4上运行,我使用passport通过api与bearer token进行身份验证。一切正常,但当未经授权的用户尝试访问需要身份验证的资源时,用户会收到错误消息405 method not allowed enter image description here

但我希望回复为401 unauthorized。  如何改变这一点,并仅发送带有消息的响应,而不是异常?我做过研究,但找不到任何东西。我使用标准laravel中间件进行授权auth:api。我的路线分组在中间件

Route::group(['middleware' => 'auth:api'], function () {
  // these routes should return 401 if user not authenticated
}

1 个答案:

答案 0 :(得分:5)

方法不允许异常发生,因为您遇到了错误的端点。您将发布到get或vice verca。

但是,如果您转到App\Exception打开handler.php in render()方法,则可以修改例外情况,您可以根据需要调整例外情况:

public function render($request, Exception $exception)
{
    if($exception instanceof \Illuminate\Auth\AuthenticationException ){

            return response('unauthorized', 401);

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

handler()方法上,只检查$exception是否是任何异常对象的实例,如果是,您可以根据需要修改响应。对于laravel例外,请遵循link