Laravel 10中Auth Middleware无法正常工作问题排查
问题:Laravel认证成功后Auth::user()为null,路由持续重定向至登录页
问题背景
在Laravel项目中为部分路由添加auth中间件后,即便登录认证成功,页面仍会持续重定向到登录页,调试发现Auth::user()始终返回null。但未启用auth中间件时,登录后能正常通过Auth::user()获取用户信息并跳转至对应页面。
相关代码如下:
自定义Authenticate中间件
namespace App\Http\Middleware; use Illuminate\Auth\Middleware\Authenticate as Middleware; use Illuminate\Http\Request; class Authenticate extends Middleware { /** * Get the path the user should be redirected to when they are not authenticated. */ protected function redirectTo(Request $request): ?string { return $request->expectsJson() ? null : route('login'); } }
AuthController登录核心逻辑
<?php namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Auth; class AuthController extends Controller { public function login_view(){ return view('auth.Login'); } public function login(Request $request){ $request->validate([ 'email' => 'required|email', 'password' => 'required' ]); $user = User::where('email', $request->email)->first(); if (!$user) { return redirect()->back()->with('error', 'User with this email does not exist'); } try { if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) { $user = Auth::user(); session()->put('user_id', $user->user_id); session()->put('type', $user->type); if ($user->type == 'User') { return redirect('Home'); } else { return redirect('Dashboard'); } } else { dd($e->getMessage()); } } catch (\Exception $e) { dd($e->getMessage()); } } // 注册、找回密码等其他方法省略... }
web.php路由配置
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\AuthController; Route::group(['middleware' => 'auth'],function () { Route::get('/Home', function () { return view('Home'); })->name('Home'); Route::get('/Profile', function () { return view('Profile'); })->name('Profile'); Route::get('/Logout', [AuthController::class, 'logout_view'])->name('Logout'); Route::post('/Logout', [AuthController::class, 'logout'])->name('Logout'); }); Route::get('/login', [AuthController::class, 'login_view'])->name('login'); Route::post('/login', [AuthController::class, 'login'])->name('login'); // 注册、找回密码等其他路由省略...
User模型
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use HasFactory; protected $table = 'USERS'; }
原因分析
核心问题在于User模型未指定自定义主键:Laravel默认使用id作为用户表的主键字段,但你的用户表使用的是user_id作为主键。当Auth::attempt()认证成功后,Laravel无法正确识别主键字段,导致无法在会话中持久化用户信息,最终Auth::user()返回null,auth中间件判定用户未认证,从而重定向到登录页。
解决方案
1. 在User模型中声明自定义主键
修改User模型,添加主键字段的声明:
namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use HasFactory; protected $table = 'USERS'; // 指定表的主键字段为user_id protected $primaryKey = 'user_id'; // 如果user_id不是自增整数类型,需添加以下配置(根据实际情况调整) // public $incrementing = false; // protected $keyType = 'string'; }
2. 移除冗余的Session手动存储代码
Laravel的Auth组件会自动管理用户会话,无需手动将用户信息存入session,删除登录逻辑中以下两行代码:
session()->put('user_id', $user->user_id); session()->put('type', $user->type);
后续获取用户类型可直接使用Auth::user()->type。
3. 清除Laravel缓存
修改模型配置后,执行以下命令清除缓存,确保配置生效:
php artisan cache:clear php artisan config:clear php artisan route:clear
4. 验证路由中间件(可选)
确认web.php中的路由是否自动应用了web中间件组(Laravel默认会自动为web.php路由添加该中间件),web中间件包含会话管理、CSRF保护等核心功能,是认证生效的基础。可在RouteServiceProvider.php中查看:
protected function mapWebRoutes() { Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); }
完成以上操作后,重新登录即可正常获取Auth::user()信息,auth中间件也会正确识别已认证状态,不再重定向到登录页。
内容的提问来源于stack exchange,提问作者Shubham Kandalgaonkar
相关产品推荐
相关产品推荐

