You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Laravel Sanctum登录成功后出现异常302重定向问题

问题:Laravel Sanctum登录成功后302重定向无法进入仪表盘

部署服务器后,登录操作已成功触发(收到登录通知邮件),但跳转至/admin/overview时返回302重定向,最终停留在登录页面;本地开发环境运行无任何问题。已尝试修改路由、直接通过PHP登录、设置请求头(accept: application/json、content-type: application/json),均未解决问题。

可能的原因及解决方法

1. Sanctum状态域配置错误

服务器环境下,Sanctum需要明确允许当前域名的会话认证:

  • 编辑config/sanctum.php,确保stateful数组包含服务器域名:
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
    '%s%s',
    'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
    env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
  • 检查.env文件,将APP_URL设置为服务器的真实域名(如https://your-domain.com),而非localhost。

2. 会话凭证未正确传递

前端请求需开启凭证携带,确保Sanctum的会话Cookie被正确保存并随跳转请求发送:

  • 修改Axios登录请求,添加withCredentials配置:
axios
    .post(`/api/admin/auth/login`, data, {
        responseType: "json",
        withCredentials: true // 新增此行
    })
  • 编辑config/cors.php,开启凭证支持:
'allowed_origins' => ['*'], // 或指定前端域名
'allowed_methods' => ['*'],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true, // 确保此处为true

3. 认证守卫一致性问题

登录时使用Auth::attempt()默认调用web守卫,但Web路由使用auth:sanctum中间件,需确保会话认证逻辑统一:

  • 在config/auth.php中确认defaults.guard为web,或显式指定守卫:
if (Auth::guard('web')->attempt($credentials)) {
    // 原登录逻辑
}

4. 服务器缓存干扰

服务器端可能存在路由、配置缓存,执行以下命令清除缓存:

php artisan route:clear
php artisan config:clear
php artisan cache:clear
php artisan view:clear

原始代码

API路由

Route::group(['prefix' => 'admin/auth'], function () {
    route::post('/login',[AuthController::class,'login'])->name('api_login'); 
    Route::get('/logout', [AuthController::class, 'logout'])->name('api_logout');
});

Web路由

Route::middleware('auth:sanctum')->prefix('admin')->group(function (){
    Route::get('/overview', [OverviewController::class, 'index'])->name('overview');
    Route::get('/orders', [OrdersController::class, 'index'])->name('orders');
});

AuthController登录方法

public function login(LoginRequest $request)
{
    try {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            $user = Auth::user();
    
            if ($user->email_verified_at !== null) {
                // 生成Sanctum令牌
                $token = $user->createToken('auth-token')->plainTextToken;

                $ipAdress = $request->ipinfo->ip;
                // 发送登录提醒邮件
                Mail::to($request->email)->send(new LoginAlert([
                    "CustomerName" => showUserName(),
                    "IpAdress"     => $ipAdress,
                    "Location"     => $request->ipinfo->country_name . ', ' . $request->ipinfo->city,
                    "BrowserOs"    => $request->header('User-Agent')
                ]));

                return ApiResponse::sendResponse(200, 'Authorized successfully', ['token' => $token]);
            }
            return ApiResponse::sendResponse(401, 'Email has not been verified', null);
        }
    
        return ApiResponse::sendResponse(401, 'Unauthorized', null);
    } catch (\Exception $th) {
        return ApiResponse::sendResponse(401, $th->getMessage(), null);
    }
}

Axios登录函数

function login() {
    document.getElementById("login-f").addEventListener("submit", function(event) {
        event.preventDefault();
    });
    let crsf_token = document.querySelector('meta[name="CRSF"]').getAttribute("content");
    axios.defaults.headers.common['X-CSRF-TOKEN'] = crsf_token;
    const data = {
        email: document.getElementById('email').value,
        password: document.getElementById('password').value
    };
    axios
        .post(`/api/admin/auth/login`, data, {
            responseType: "json"
        })
        .then(function (response) {
           if (response.status === 200 && response.data.msg === "Authorized successfully") {
                setTimeout(function () {
                    window.location.href = "/admin/overview";
                }, 2000);
            }
        })
        .catch(function (error) {
            // 错误处理
            console.log(error);
        });
}

内容的提问来源于stack exchange,提问作者Programming student

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 06:06:21