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:
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-storageThis 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' ); } });
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 atadmin/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 yourconfig.xmlto ensure cookies are retained between app launches:<preference name="InAppBrowserPersistentCookie" value="true" />
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:
- Enable Drupal's Services and REST Server modules
- Create an endpoint (e.g.,
/api/user/login) that accepts POST requests with username/password and returns session data - 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'); }
- 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-aioto require fingerprint/face ID before accessing saved credentials for an extra layer of security
内容的提问来源于stack exchange,提问作者Kevincore

