如何从Firebase Auth中读取自定义设置的state参数?
解决方法
方法1:解析Firebase返回的state参数
Firebase Auth在处理重定向登录时,会将你自定义的state值与它自身生成的CSRF保护state拼接后传递。当用户完成认证返回页面时,你可以从当前URL的state查询参数中提取完整值,再拆分出自定义部分:
// 发起登录前设置自定义state const googleAuthProvider = new firebase.auth.GoogleAuthProvider(); googleAuthProvider.setCustomParameters({ state: "myValue" }); await firebase.auth().signInWithRedirect(googleAuthProvider); // 回调页面中解析state const urlParams = new URLSearchParams(window.location.search); const fullState = urlParams.get('state'); // Firebase会将自定义state放在最后,以换行符分隔 const customState = fullState.split('\n').pop(); console.log(customState); // 输出 "myValue"
注意:这种方法依赖Firebase内部拼接规则,可能随版本变化,稳定性一般。
方法2:使用本地存储传递自定义值(推荐)
更可靠的方式是在发起登录前将自定义值存入sessionStorage,登录完成后再读取:
// 发起登录前存储自定义值 sessionStorage.setItem('customLoginState', 'myValue'); const googleAuthProvider = new firebase.auth.GoogleAuthProvider(); await firebase.auth().signInWithRedirect(googleAuthProvider); // 回调页面中读取值 firebase.auth().getRedirectResult().then((result) => { if (result.user) { const customState = sessionStorage.getItem('customLoginState'); console.log(customState); // 输出 "myValue" // 读取后清除存储,避免重复使用 sessionStorage.removeItem('customLoginState'); } }).catch((error) => { // 处理登录错误 });
这种方法不依赖Firebase内部实现,兼容性和稳定性更好。需要注意的是,要在页面加载时立即调用getRedirectResult获取登录结果,同时读取存储的自定义值。
内容的提问来源于stack exchange,提问作者user20326571
相关产品推荐
相关产品推荐

