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

Laravel与Cordova交互时Session ID每次请求均变更问题求助

问题分析与解决方案

核心问题总结

Postman中使用Laravel Sanctum Bearer Token请求时会话稳定,Session ID不变且能正常获取用户信息;但Cordova中每次请求的Session ID都变更,虽存在laravel_session Cookie但会话无法维持。

分步排查与解决

1. 修复后端代码明显错误

你的UserController中存在提前返回Session ID的代码,导致后续用户认证逻辑完全无法执行,这是首要问题:

class UserController extends Controller
{
    public function index(Request $request)
    {
        // 移除这行无效调试代码
        // $session = $request->post('session');
        // return $request->session()->getId();
        
        $user = Auth::user();
        if($user) {
            return response()->json([
                'status' => 'success',
                'data' => $user
            ]);
        } else {
            return response()->json([
                'status' => 'error',
                'message' => 'Unauthorized'
            ], 401);
        }
    }
}

2. 确保Cordova请求携带Cookie

Cordova WebView默认不会自动携带Cookie,需在AJAX请求中开启凭证携带:

$.ajax({
    url: 'http://localhost:5000/api/user',
    method: 'GET',
    headers: {
        'Authorization': 'Bearer ' + $token,
    },
    xhrFields: {
        withCredentials: true // 关键配置:允许携带Cookie
    },
    dataType: 'json',
    success: function(response) {
        console.log(response);
        localStorage.setItem("user", JSON.stringify(response.data)); // 注意转存字符串格式
        return response;
    },
    error: function(response) {
        console.log(response);
        app.views.main.router.navigate('/sign-in/', {reloadCurrent: true});
    }
});

3. 配置Laravel Sanctum与CORS

Sanctum 可信域名配置

修改.env添加Cordova调试域名:

SANCTUM_STATEFUL_DOMAINS=localhost,localhost:5000,localhost:8080 # 根据你的Cordova端口调整

CORS 允许凭证

修改config/cors.php:

'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'], // 生产环境建议指定具体域名
'allowed_headers' => ['*'],
'supports_credentials' => true, // 必须设为true

4. 调整Session Cookie属性

修改config/session.php适配Cordova WebView:

'same_site' => 'lax', // 调试环境可设为'lax',生产环境若用HTTPS可设为'none'
'secure' => env('SESSION_SECURE_COOKIE', false), // 本地调试关闭secure

5. 完善SPA登录流程(关键)

Sanctum的SPA模式依赖CSRF Cookie维持会话,登录前需先获取CSRF令牌:

// 先获取CSRF Cookie
$.ajax({
    url: 'http://localhost:5000/sanctum/csrf-cookie',
    method: 'GET',
    xhrFields: {withCredentials: true},
    success: function() {
        // 发起登录请求
        $.ajax({
            url: 'http://localhost:5000/api/login',
            method: 'POST',
            xhrFields: {withCredentials: true},
            data: {email: 'your-email', password: 'your-password'},
            success: function(res) {
                $token = res.token; // 保存返回的Bearer Token
                // 再请求用户信息接口
                // ... 调用你的user接口请求代码
            }
        });
    }
});

6. Cordova WebView配置优化

修改config.xml添加WebView权限:

<!-- 通用配置 -->
<preference name="AllowFileAccess" value="true" />
<preference name="AllowUniversalAccessFromFileURLs" value="true" />

<!-- iOS 适配WKWebView -->
<platform name="ios">
    <preference name="WKWebViewOnly" value="true" />
    <feature name="CDVWKWebViewEngine">
        <param name="ios-package" value="CDVWKWebViewEngine" />
    </feature>
    <preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" />
</platform>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 12:17:35