【问题标题】:Laravel 5 Basic Auth custom errorLaravel 5 Basic Auth 自定义错误
【发布时间】:2016-09-07 00:13:55
【问题描述】:

在 Laravel 5 中,如果用户的基本身份验证失败,则返回的默认消息是“Invalid Credentials”错误字符串。发生这种情况时,我正在尝试返回自定义 JSON 错误。

我可以在 vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php 中编辑返回的响应 但是,我还没有看到您可以在供应商目录之外更改此消息的行为的位置。有办法吗?

看起来有一些方法可以通过 Laravel 4 做到这一点:Laravel 4 Basic Auth custom error

【问题讨论】:

    标签: php laravel-5 basic-authentication


    【解决方案1】:

    想通了,看来我必须创建自定义中间件来处理这个问题。 请注意,此解决方案在从浏览器调用我的 API 时不起作用,只有在从 Postman 之类的工具调用它时才起作用。由于某种原因,从我的浏览器调用它时,我总是在看到基本身份验证提示之前收到错误。

    在我的控制器中,我将中间件更改为我新创建的:

    $this->middleware('custom');
    

    在内核中我为它添加了位置:

    protected $routeMiddleware = [
        'auth.basic.once' =>  \App\Http\Middleware\Custom::class,
    ]
    

    然后我创建了中间件。我在创建 API 时使用了无状态基本身份验证:

    <?php
    namespace App\Http\Middleware;
    
    use Auth;
    use Closure;
    use Illuminate\Http\Request as HttpRequest;
    use App\Entities\CustomErrorResponse
    class Custom
    {
        public function __construct(CustomErrorResponse $customErrorResponse) {
            $this->customErrorResponse = $customErrorResponse
        }
         public function handle($request, Closure $next)
         {   
             $response = Auth::onceBasic();
    
             if (!$response) {
                 return $next($request);
             }
             return $this->customErrorResponse->send();
     }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-07
      • 2017-07-14
      • 2016-04-17
      • 2019-12-05
      • 2017-08-20
      • 2015-09-07
      • 2017-08-17
      • 1970-01-01
      相关资源
      最近更新 更多