我正在对匿名用户使用 firebase 身份验证。 当用户在网站上注册时,我们会链接他们的凭据。
这是代码:
//Create the email and password credential, to upgrade the anonymous user.
let credential = firebase.auth.EmailAuthProvider.credential(email, visitorId);
//Link the credential to the currently signed in user (the anonymous user).
auth.currentUser.link(credential).then((user) => {
console.log("anonymous visitor successfully upgraded");
},
(error) => {
//error upgrading the anonymouse user
console.log("Error upgrading anonymous visitor", error);
});
以下是此方法的文档
直到今天,这一直运作良好。 现在我突然收到一个错误代码:身份验证/网络请求失败。
如果我在 Fiddler 中检查失败的请求,我会发现以下响应:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalid",
"message": "TOKEN_EXPIRED"
}
],
"code": 400,
"message": "TOKEN_EXPIRED"
}
}
奇怪的是,如果我在请求中解码令牌,到期日期将在未来(大约提前 1 小时,这是其令牌的默认时间长度)。 在我生成令牌的时间和我尝试将其链接到用户的时间之间几乎没有延迟。 那么为什么会失败呢?
我的研究:
这里的问题听起来很相似,但我还没有为我解决它。
Firebase 的支持团队要求的第一件事是简化该问题的演示。 我应该先这样做。 我的坏。 为了其他人的利益,我在下面包含了演示代码。 它没有问题。 所以我们的问题显然出在我们的实施上。
我回到了网络请求。 第一个线索来自我意识到响应firebase.auth().currentUser.link(credential)发送的网络请求显示为已取消。 使用 chrome://net-internals/#events,我发现 --> net_error = -3 (ERR_ABORTED)。
这意味着在返回 firebase 请求之前,某些内容正在重定向页面。 逐步浏览代码时,我发现正在触发一个Google跟踪代码管理器HTML代码段,其中包括单击特定元素时的重定向。
删除了它,问题自行解决了。 我希望这个验尸证明对其他人有用。
<html>
<head>
<meta charset="utf-8">
<script src="https://www.gstatic.com/firebasejs/3.6.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.6.2/firebase-auth.js"></script>
<script>
window.config = {
apiKey: "<apikey>",
authDomain: "<authDomain>",
databaseURL: "<databaseUrl>",
};
//initialize the app
firebase.initializeApp(window.config);
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in.
console.log("User is signed in:" + user.uid);
} else {
// No user is signed in.
console.log("no user so sign in anonymously");
firebase.auth().signInAnonymously().catch((error) => {
console.log("marketing.visitor:" + error.code + " " + error.message);
});
}
});
function signInWithEmailAndPassword(){
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue = false; // for IE as dont support preventDefault;
}
var myElement = document.getElementById("lead_email");
console.log(myElement.value);
//Create the email and password credential, to upgrade the anonymous user.
let credential = firebase.auth.EmailAuthProvider.credential(myElement.value, firebase.auth().currentUser.uid);
//Links the credential to the currently signed in user (the anonymous user).
firebase.auth().currentUser.link(credential).then((user) => {
console.log("anonymous visitor successfully upgraded");
},
(error) => {
console.log("error upgrading anonymous user", error);
});
return false;
}
</script>
</head>
<body>
<form onsubmit="signInWithEmailAndPassword()">
<label class="form-field" for="lead_email">Email Address:</label>
<input data-name="lead_email" id="lead_email" maxlength="256" name="lead_email" required="required" type="email">
<input type="submit" value="Submit">
</form>
</body>
</html>