[英]firebase.auth().onAuthStateChanged not firing with Authorized domains
[英]Javascript - firebase.auth().onAuthStateChanged not firing upon login/logout
我有以下代码:
var config = {
apiKey: "xxxxx",
authDomain: "xxxxx",
databaseURL: "xxxxx",
projectId: "xxxxx",
storageBucket: "xxxxx",
messagingSenderId: "xxxxx"
};
firebase.initializeApp(config);
$("#loginButton").on('click', function(){
logIn($("#email").val(), $("#pwd").val());
});
$("#logoutButton").on('click', function(){
firebase.auth().signOut();
console.log("clicked logout button");
});
function logIn(email, password){
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
alert(error.message);
});
}
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log("Signed in");
firebase.auth().currentUser.getIdToken(true).then(function(idToken) {
// Send token to your backend via HTTPS
// ...
console.log("Token = " + idToken);
console.log("Logged in!");
$("#loginButton").val(idToken);
$("#loginForm").submit();
}).catch(function(error) {
// Handle error
console.log(error);
});
}
else{
console.log("User signed out");
}
});
我要在这里完成的是:用户填写 email 和密码字段,单击带有id="loginButton"
的按钮,我登录,获取令牌 ID 并将其发送到服务器(这种形式是骇人听闻的发送方式吗它推荐?)并通过我的快速应用程序(Node.js)中的管理员 SDK 验证令牌 ID。
重点是。 用户确实登录并注销(通过刷新页面我可以看到打印了“已登录”和“用户已注销”)。
但是为什么onAuthStateChanged
应该观察/监听 auth state 上的每个更改时只调用一次?
为什么我可以登录和注销,但onAuthStateChanged
仅在开始时(页面加载时)被调用,而在单击按钮( loginButton
和logoutButton
)时不再被调用?
首先,在您的身份验证状态侦听器中将firebase.auth().currentUser.getIdToken
更改为user.getIdToken
。
其次,您应该添加一个then到signInWithEmailPassword承诺并打印一些消息以查看登录是否成功。
最后,如果您在两次登录同一用户而没有在其间注销,则不会触发身份验证状态侦听器。 如果您想在每次用户登录时触发某些逻辑,则应将其放入signInWithEmailPassword承诺的then块中。
虽然这是一个老问题,但似乎有些人仍在为此苦苦挣扎。
我遇到了同样的问题, onAuthStateChange 没有在 SignOut 上被触发,我意识到这是因为我在注销之前取消了对监听器的订阅,所以当我注销时,已经没有监听器了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.