【问题标题】:Laravel 7: How to prevent middleware Authenticate from redirecting when user is not authenticated?Laravel 7:当用户未通过身份验证时,如何防止中间件身份验证重定向?
【发布时间】:2020-09-16 06:11:17
【问题描述】:

我已经使用$this->middleware('auth:api'); 实现了中间件身份验证。

应用程序是一个 REST API,所以我不需要 Laravel 来重定向客户端。我需要它来返回 JSON 响应。

App\Http\Middleware\Authenticate.php; 内部有一个方法redirectTo。此方法只接受一个路由,因此我无法将 JSON 响应添加到此方法。

如何使用中间件验证(auth:api)并在用户未通过身份验证时返回JSON响应?

【问题讨论】:

    标签: laravel laravel-7


    【解决方案1】:

    当请求需要 JSON 响应时,Laravel 已经这样做了。因此,只要您发送 AJAX 请求或发送带有正确设置的 Accept 标头的请求(application/json*),Laravel 就会自动响应 401 JSON 响应。

    【讨论】:

      【解决方案2】:
      <?php
      
      namespace App\Http\Middleware;
      
      use Illuminate\Auth\Middleware\Authenticate as Middleware;
      
      class Authenticate extends Middleware
      {
          /**
           * Get the path the user should be redirected to when they are not authenticated.
           *
           * @param  \Illuminate\Http\Request  $request
           * @return string|null
           */
          protected function redirectTo($request)
          {
              if (! $request->expectsJson()) {
                  return route('login');
              }
          }
      }
      

      这个类扩展了Illuminate\Auth\Middleware\Authenticate - 它覆盖了redirectTo 方法。你需要写下你自己的句柄方法。如果您不需要框架的身份验证方法,则可以删除 extends 部分。

      public function handle($request, Closure $next, ...$guards)
      {
          if (Auth::guest()) {
              return response()->json(['message' => 'you shall not pass']);
          }
      
          // other checks
      
          return $next($request);
      }
      

      另一个选择是保留extends 并在定期检查是否需要基类的某些功能后调用父方法。

      public function handle($request, Closure $next, ...$guards)
      {
          if (Auth::guest()) {
              return response()->json(['message' => 'you shall not pass']);
          }
      
          return parent::handle($request, $next, $guards);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-15
        • 1970-01-01
        • 2015-02-24
        • 2021-06-19
        • 2017-01-04
        • 2019-04-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多