我尝试通过调用Auth::user()
来检查用户是否通过身份验证的中间件
但它返回null。我将此中间件称为protected $middleware
中Kernel.php
部分列表的最后一个。有没有办法从中间件检查用户是否经过身份验证或我应该如何以其他方式进行检查?
另外:我正在使用Zizaco Entrust。可能是它不起作用的原因 我正在使用Laravel 5.5
我的app / HTTP / Kernel.php:
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\FirstLoginPasswordChange::class,
];
我的FirstLoginPasswordChange中间件:
use Illuminate\Support\Facades\Auth;
use Zizaco\Entrust\Entrust;
public function handle($request, Closure $next)
{
dd(Auth::user()); // returns null
// or
dd(Auth::check()); // returns false
// or
dd(\Entrust::user()); // returns null
return $next($request);
}
}
答案 0 :(得分:1)
protected $middleware
部分的中间件移动到Kernel.php中的protected $routeMiddleware
部分来解决问题
使用这篇文章:
http://laraveldaily.com/password-expired-force-change-password-every-30-days/
答案 1 :(得分:0)
要检查用户是否经过身份验证,您可以像Laravel Docs所述:
use Illuminate\Support\Facades\Auth; //be sure to add the facade
if (Auth::check()) {
// The user is logged in...
}
如果您正在尝试获取用户详细信息并执行某些逻辑,那么您可以在中间件中执行此操作:
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$role = Auth::user()->role; //Obtenemos el rol del usuario
if ($role != "user"){
return redirect('/logout');
}
return $next($request);
}
}