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

Flutter HTTP请求无法维持CodeIgniter Session的技术咨询

Flutter + CodeIgniter Session Persistence: Fixing Unauthorized Errors

Hey there! Let's tackle your session persistence issue between Flutter and CodeIgniter's REST API. The problem you're seeing is totally normal—Flutter's default http package doesn't automatically persist cookies (like the ci_session cookie that CodeIgniter uses) across requests, so each call creates a new session. Here's how to fix it, plus answers to your server-side session question.

1. Fixing Flutter Side: Persist Session Cookies

You'll need to extract the session cookie after login and include it in every subsequent request.

First, save the session cookie after successful login:

import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

Future<bool> login(String username, String password) async {
  final loginUrl = "https://your-api-domain.com/login";
  final response = await http.post(
    Uri.parse(loginUrl),
    body: {'username': username, 'password': password},
  );

  if (response.statusCode == 200) {
    // Extract the session cookie from the 'set-cookie' header
    String sessionCookie = response.headers['set-cookie'] ?? '';
    // Persist the cookie using SharedPreferences for future requests
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('ci_session', sessionCookie);
    return true;
  }
  return false;
}

Then, update your ApiCall class to include the saved cookie in all requests:

class ApiCall {
  static Future<Map> getData(String url) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String sessionCookie = prefs.getString('ci_session') ?? '';

    final response = await http.get(
      Uri.parse(url),
      headers: {'Cookie': sessionCookie},
    );
    return json.decode(response.body);
  }

  static Future<Map> postData(String url, Map data) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String sessionCookie = prefs.getString('ci_session') ?? '';

    try {
      final response = await http.post(
        Uri.parse(url),
        body: data,
        headers: {'Cookie': sessionCookie},
      );
      return json.decode(response.body);
    } catch (error) {
      print(error.toString());
      return {'status': false, 'message': error.toString()};
    }
  }
}

The dio package handles cookie persistence out of the box, which is way simpler. First add it to your pubspec.yaml:

dependencies:
  dio: ^5.4.0

Then use it for all API calls—no manual cookie handling needed:

import 'package:dio/dio.dart';

final dio = Dio();

// Login request (automatically saves session cookie)
Future<bool> login(String username, String password) async {
  try {
    await dio.post(
      "https://your-api-domain.com/login",
      data: {'username': username, 'password': password},
    );
    return true;
  } catch (e) {
    print(e);
    return false;
  }
}

// Subsequent requests automatically carry the session cookie
class ApiCall {
  static Future<Map> getData(String url) async {
    final response = await dio.get(url);
    return response.data;
  }

  static Future<Map> postData(String url, Map data) async {
    try {
      final response = await dio.post(url, data: data);
      return response.data;
    } catch (error) {
      print(error.toString());
      return {'status': false, 'message': error.toString()};
    }
  }
}

2. Server-Side CodeIgniter Configuration

You need to make sure CodeIgniter is set up to accept cross-origin requests with cookies, and that session settings are mobile-friendly.

Update Session Config

Open application/config/config.php and verify these settings:

$config['sess_driver'] = 'database'; // Use database for reliable session storage (recommended)
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200; // 2 hours, adjust as needed
$config['sess_save_path'] = 'ci_sessions'; // Your session table name (if using database)
$config['sess_match_ip'] = FALSE; // Mobile devices often change IPs, set to false
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;

Enable CORS with Credentials

Add these headers to your CodeIgniter API controller (or create a global hook to apply to all API routes):

header("Access-Control-Allow-Origin: *"); // Replace with your Flutter app's domain/IP for better security
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Cookie");
header("Access-Control-Allow-Credentials: true"); // Critical for allowing cookie transmission across origins

3. Can You Manage Sessions via the Web App?

Absolutely! CodeIgniter stores session data on the server (either in the database or file system), so your web application and Flutter app can share the same session as long as they both send the correct ci_session cookie.

This means:

  • A user logging in via the web app will have their session recognized by the Flutter app if you pass the same cookie.
  • You can manage sessions directly from the web app (e.g., force logout, update user permissions) because all session data lives on the server—changes will apply to both web and mobile clients instantly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:28:51