React Native Mobile应用程序与Expo中的Cookie问题



我正在创建这个Native Mobile应用程序,它基本上是在Webview中托管一个Web应用程序,我的任务是在Native中构建登录页面,因为客户端希望使用生物特征登录。问题是,我能够创建登录页面设置路由,并向登录端点发出请求。问题是登录请求以cookie的形式返回身份验证。

async function login(event) {
const response = await fetch(`https://xxxxx.xxxx.xx.xxx/api/v1/login.json`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: userName,
password: password,
remember_device: true,
workgroup_code: 'XXXX',
accessor_id: null,
origin: 'xxx'
})
});
if (response.ok) {
const data = await response.json();
// console.log(JSON.stringify(data));
authObj = data;
if (authObj.restrictions.find(x => x === 'verify_device')) {
navigation.navigate('Device');
}
} else {
alert(`Bad username or password.
Need help logging in?
Call X-XXX-XXX-XXXX`);
}

}

正如你所看到的,有时我需要将成功登录发送到一个验证屏幕,该屏幕在webview中加载Web应用程序:

<WebView 
javaScriptEnabled={true}
style={styles.container}
source={{ uri: 'https://xxxx-staging.xxx.com/#/login/restriction/verify_device' }}
sharedCookiesEnabled={true}
injectedJavaScriptBeforeContentLoaded={runFirst}
injectedJavaScript={runLast}
onMessage={(event) => {
console.log('event: ', event);
}}
/>

runFirst在本地存储中设置一些正常工作的值:

const runFirst = `
window.localStorage.setItem('workgroup_code', ${authObj.workgroup_code});
window.localStorage.setItem('accessor_id', ${authObj.mpv_device_id});
true; // note: this is required, or you'll sometimes get silent failures

`;

runLast只是我测试的一些示例代码:

const runLast = `
alert('Me');
alert(window.document.cookies);
true;

`;

问题是为了让Webview中的这个页面正常工作,它需要有一组像这样的cookie:

上面login请求中的_xxx_web_session_staging,我如何将请求cookie传递到Webview页面??

所以你知道,我尝试过CookieManager,但我找不到一种方法让它在我的Expo应用程序中工作,也不知道如何将值传递到WebView。

正如你所看到的,我正在使用sharedCookiesEnabled={true},我不知道我是否遗漏了什么。

我真的很感谢在这方面的任何帮助或建议。

我通过解析获取请求的响应来解决这个问题:

loginCookie = JSON.stringify(response.headers.map['set-cookie']);
and then setting the cookie value manually:
const runFirst = `
window.document.cookie = ${loginCookie};
true; // note: this is required, or you'll sometimes get silent failures
`;

最新更新