【问题标题】:Laravel - I Auth::user() in Authenticate.php Middleware return nullLaravel - 我在 Authenticate.php 中间件中的 Auth::user() 返回 null
【发布时间】:2022-10-02 14:03:34
【问题描述】:

当我尝试返回 Auth::user() 或返回 $request->user() 时,handle($request, Closure $next, ...$guards) 函数(在 Authenticate.php 中间件中)返回 null。该中间件为每条路由执行。我正在尝试返回 Auth::user() 因为我需要当前登录用户的电子邮件,返回 Auth::user() 是为了检查我是否可以获得有关当前登录用户的信息。

<?php

namespace App\\Http\\Middleware;

use Illuminate\\Auth\\Middleware\\Authenticate as Middleware;
use Closure;
use Illuminate\\Support\\Facades\\Cookie;
use PHPOpenSourceSaver\\JWTAuth\\Exceptions\\TokenExpiredException;
use PHPOpenSourceSaver\\JWTAuth\\Exceptions\\TokenInvalidException;
use PHPOpenSourceSaver\\JWTAuth\\Facades\\JWTAuth;
use Symfony\\Component\\Routing\\Exception\\RouteNotFoundException;

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\');
        }
    }

    public function handle($request, Closure $next, ...$guards)
    {
        return Auth::user();
        return $next($request);
    }
}
  • 返回Auth::user()?归还到哪里?
  • 我正在尝试用邮递员退回它
  • 欢迎来到 SO...什么是默认守卫?
  • \'guards\' => [ // \'web\' => [ // \'driver\' => \'session\', // \'provider\' => \'users\', // ], \'api\' => [ \'driver\' => \'jwt\', \'provider\' => \'users\', ], ],
  • 默认设置是什么?请将此信息添加到您的答案中,而不是在 cmets 中的代码块中

标签: php laravel null middleware


【解决方案1】:

父类Illuminate\Auth\Middleware\Authenticate 中的handle() 方法执行实际的身份验证。由于您已覆盖此方法且未调用身份验证逻辑,因此不会执行身份验证,因此 Auth::user() 返回 null。

您可以从中间件中删除handle() 方法,并在redirectTo() 中添加调试行return Auth::user();(就在if() 之前)。

【讨论】:

    猜你喜欢
    • 2019-09-20
    • 2016-05-13
    • 2020-08-14
    • 1970-01-01
    • 2023-02-04
    • 2017-03-17
    • 1970-01-01
    • 2021-01-02
    • 2017-06-29
    相关资源
    最近更新 更多