【问题标题】:How change UnauthorizedHttpException errorHandler auth.basic in Laravel如何在 Laravel 中更改 UnauthorizedHttpException errorHandler auth.basic
【发布时间】:2020-01-27 17:22:38
【问题描述】:

我正在尝试在 Laravel 5.5.48 中使用基本身份验证制作 api
当验证成功时('username' and 'password')响应是正确的,但是如果验证不成功(wrong 'username' and 'password' data)显示错误

我没有尝试过,但我无法更改响应中的异常显示 (response()->json(['status'=>'auth failed']))

路由/api.php

Route::post('/index', 'Api\MyController@index')->middleware('auth.basic');

app/Http/Controllers/Api/MyController@index

public function index(Request $request)
{
    return response()->json(array('status' => 'success'));
}

【问题讨论】:

    标签: php laravel api authentication


    【解决方案1】:

    您可以使用Exception handler:

    app/Exceptions/Handler.php内:

    public function render($request, Exception $exception)
    {
        if ($exception instanceof UnauthorizedException) {
            return response()->json(['status'=>'auth failed'], Response::HTTP_UNAUTHORIZED);
        }
    
        return parent::render($request, $exception);
    }
    

    别忘了使用UnauthorizedException 和Response:

    use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
    use Symfony\Component\HttpFoundation\Response
    

    查看here 了解有关 Laravel 异常处理程序的更多详细信息。

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      请注意,您收到的错误是设计用来帮助您在 localhost 中进行调试的,如果您将 APP_ENV 更改为“生产”和 APP_DEBUG=false ,它将不会显示整个错误堆栈

      但是,要捕获错误并手动处理,请在 App\Exceptions\Handler 中返回自定义响应

      public function render($request, Exception $exception)
      {
          if ($exception instanceof Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException) {
              return response()->json(['status'=>'auth failed'], 401);
          }
          return parent::render($request, $exception);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-06
        • 2021-07-29
        • 2019-03-10
        • 1970-01-01
        • 2019-04-11
        • 2015-08-29
        • 2018-09-03
        • 2014-02-01
        相关资源
        最近更新 更多