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

Cordova inAppBrowser存储复用凭证:解决跨平台自动登出重登问题

Hey there, let's work through this auto-logout and seamless re-login issue for your Cordova + Drupal 7 app. Here are practical, actionable solutions you can implement right away:

1. Securely Store Credentials & Auto-Fill Login Forms

Since your users are getting logged out periodically, the most straightforward fix is to securely save their username/password (with explicit consent) and auto-populate the login form when needed. Use a secure storage plugin instead of plain localStorage to avoid exposing sensitive data.

Step-by-Step Implementation:

  • Install the Secure Storage Plugin:

    cordova plugin add cordova-plugin-secure-storage
    

    This plugin encrypts data at rest, which is critical for storing passwords.

  • Save Credentials After First Login:
    When your user successfully logs in and agrees to save their info, store the credentials:

    // Initialize the secure storage container
    const secureStorage = new cordova.plugins.SecureStorage(
      () => console.log('Secure storage ready'),
      (err) => console.error('Storage init failed:', err),
      'drupalAppAuth'
    );
    
    // Save username and password (trigger this only after user consent)
    function saveCredentials(username, password) {
      secureStorage.set(
        (key) => console.log(`Saved ${key}`),
        (err) => console.error(`Failed to save ${key}:`, err),
        'username',
        username
      );
    
      secureStorage.set(
        (key) => console.log(`Saved ${key}`),
        (err) => console.error(`Failed to save ${key}:`, err),
        'password',
        password
      );
    }
    
  • Auto-Fill & Submit Login Form:
    When launching the InAppBrowser, listen for page load events. If the login page loads, pull the saved credentials and inject JavaScript to fill/submit the form:

    const browser = cordova.InAppBrowser.open('https://your-drupal-mobile-site.com', '_blank', 'location=no');
    
    browser.addEventListener('loadstop', (event) => {
      // Check if we're on the Drupal login page (adjust URL match as needed)
      if (event.url.includes('/user/login')) {
        // Fetch username and populate the field
        secureStorage.get(
          (username) => {
            browser.executeScript({
              code: `document.getElementById('edit-name').value = '${username}';`
            });
          },
          (err) => console.error('Failed to get username:', err),
          'username'
        );
    
        // Fetch password, populate, and auto-submit (optional)
        secureStorage.get(
          (password) => {
            browser.executeScript({
              code: `document.getElementById('edit-pass').value = '${password}';`
            });
            // Auto-submit only if you're confident the form IDs are consistent
            browser.executeScript({
              code: "document.getElementById('user-login-form').submit();"
            });
          },
          (err) => console.error('Failed to get password:', err),
          'password'
        );
      }
    });
    
2. Reduce Auto-Logout Frequency (Complementary Fix)

The auto-logout might be caused by short Drupal session timeouts or InAppBrowser cookie persistence issues. Fix these to minimize how often users need to re-login:

  • Adjust Drupal Session Settings:
    Go to your Drupal admin panel at admin/config/people/sessions:

    • Increase the Session timeout value (e.g., to 43200 seconds = 12 hours)
    • Enable "Remember me" by default so sessions persist longer
  • Configure InAppBrowser for Persistent Cookies:
    Add this to your config.xml to ensure cookies are retained between app launches:

    <preference name="InAppBrowserPersistentCookie" value="true" />
    
3. Use Drupal REST API for Headless Login (Advanced)

For a more robust integration, use Drupal's Services module to build a REST login endpoint. This lets your Cordova app authenticate directly with Drupal, then inject the session cookie into the InAppBrowser to skip the login form entirely.

Quick Setup:

  1. Enable Drupal's Services and REST Server modules
  2. Create an endpoint (e.g., /api/user/login) that accepts POST requests with username/password and returns session data
  3. Use this code in your app to authenticate and set the session cookie:
function autoLoginViaAPI() {
  secureStorage.get((username) => {
    secureStorage.get((password) => {
      fetch('https://your-drupal-site.com/api/user/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password })
      })
      .then(res => res.json())
      .then(data => {
        // Set the session cookie in the InAppBrowser
        const sessionCookie = `${data.session_name}=${data.sessid}; path=/; domain=your-drupal-site.com`;
        browser.executeScript({ code: `document.cookie = '${sessionCookie}';` });
        // Refresh to load the authenticated page
        browser.executeScript({ code: 'window.location.reload();' });
      })
      .catch(err => console.error('API login failed:', err));
    }, err => console.error('No saved password found:', err), 'password');
  }, err => console.error('No saved username found:', err), 'username');
}
Critical Security Notes
  • Always use HTTPS: Ensure your Drupal site is served over HTTPS to prevent credential interception
  • Explicit user consent: Never save credentials without the user's clear approval
  • Add biometric protection: Pair with cordova-plugin-fingerprint-aio to require fingerprint/face ID before accessing saved credentials for an extra layer of security

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:12:42