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

启用CSRF防护后Android端无法调用CodeIgniter登录接口的解决方案咨询

Solutions for Android App Accessing CodeIgniter API with CSRF Protection Enabled

Got it, let's tackle this problem without disabling CSRF protection—smart move keeping it enabled, by the way! Here are a few solid approaches tailored for your CodeIgniter + Android setup:

1. Fetch CSRF Token First, Then Submit Login Request

CodeIgniter generates a unique CSRF token per user session, stored in a cookie and accessible via the Security class. Your Android app can first retrieve this token, then include it in the login POST request.

Backend Setup (CodeIgniter):

Add a simple endpoint to return the current CSRF token and its parameter name:

// In your AuthController or a dedicated APIController
public function get_csrf_token() {
    // Return token data as JSON
    $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'token_name' => $this->security->get_csrf_token_name(),
            'token_hash' => $this->security->get_csrf_hash()
        ]));
}

Make sure this endpoint is accessible without requiring authentication (since users haven't logged in yet!).

Android Implementation:

  1. Send a GET request to /auth/get_csrf_token (adjust the URL to match your routing).
  2. Parse the JSON response to get token_name and token_hash.
  3. Include these values in your login POST request: add a key-value pair where the key is token_name and the value is token_hash, alongside your username and password fields.

2. Pass CSRF Token via HTTP Headers

CodeIgniter supports validating CSRF tokens from HTTP headers (in addition to POST parameters), which can be cleaner for mobile apps.

Android Implementation:

After fetching the CSRF token (using the same endpoint from Option 1), instead of adding it to the POST body, include it in the request headers. Use either:

  • X-CSRF-Token (matches CodeIgniter's default header check)
  • X-XSRF-Token (alternate header name the framework also recognizes)

For example, with OkHttp:

// Assuming you have fetched tokenHash earlier
Request request = new Request.Builder()
    .url("your-login-endpoint-url")
    .addHeader("X-CSRF-Token", tokenHash)
    .post(formBody) // Form body with username/password
    .build();

No extra backend changes needed here—CodeIgniter will automatically check these headers during CSRF validation.

CodeIgniter ties CSRF tokens to user sessions via cookies. If your Android app persists cookies across requests, you can avoid manually fetching the token each time (though you'll still need to include the token value in POST/headers).

Android Implementation:

Use a cookie jar to store cookies from initial requests (like the token fetch endpoint or even the login page's GET request). Libraries like OkHttp have built-in support for this:

CookieJar cookieJar = new CookieJar() {
    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        cookieStore.put(url.host(), cookies);
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        List<Cookie> cookies = cookieStore.get(url.host());
        return cookies != null ? cookies : new ArrayList<>();
    }
};

OkHttpClient client = new OkHttpClient.Builder()
    .cookieJar(cookieJar)
    .build();

Once the CSRF cookie is stored, subsequent requests will automatically carry it. Just make sure you still include the token value in the POST body or headers as described in the previous options.

Important Notes:

  • Token Expiry: CodeIgniter's CSRF tokens expire based on $config['csrf_expire'] (default 7200 seconds). Your app should handle token expiration by re-fetching the token if a request fails with a CSRF error.
  • Avoid Hardcoding: Never hardcode a CSRF token in your Android app—always fetch it dynamically per session.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:44:44