我在我的网络应用程序中设置了电子邮件链接登录,它工作正常。但是,我需要在执行某个操作之前重新验证用户身份。
我正在使用以下代码重新进行身份验证:
let credential = firebase.auth.EmailAuthProvider.credentialWithLink(userEmail, window.location.href);
firebase.auth().currentUser.reauthenticateWithCredential(credential).then(function (usercred: any) {
console.log('Reauthentication test successful.');
}).catch(function (error: any) {
console.log('Reauthentication test failed.');
});
但是,凭证每次都会引发错误:
code: "auth/argument-error"
message: "Invalid email link!"
即使我尝试更改 URL 也是如此。该 url 在控制台中获得授权,并且是 https (我最初在 localhost 上进行测试,并认为这可能是问题所在)。
有任何想法吗?
最佳答案
我遇到了同样的问题,documentation在这个过程中有点模糊。我不想使用已经存在的 UI 解决方案(😅),所以我必须弄清楚。
这是文档片段:
import { getAuth, linkWithCredential, EmailAuthProvider } from "firebase/auth";
// Construct the email link credential from the current URL.
const credential = EmailAuthProvider.credentialWithLink(
email, window.location.href);
// Link the credential to the current user.
const auth = getAuth();
linkWithCredential(auth.currentUser, credential)
.then((usercred) => {
// The provider is now successfully linked.
// The phone user can now sign in with their phone number or email.
})
.catch((error) => {
// Some error occurred.
});
代码 window.location.href
假设您正在打开来自电子邮件链接登录的链接它与其他电子邮件链接过程没有太大区别,您必须触发从客户端或服务器发送的电子邮件。
我会得到 handle the other modes 的页面(密码重置,...)以及处理新身份验证或仅在页面加载时重新身份验证的特定逻辑。
这是基于 documentation 的 Angular (Typescript) 示例
// app.component.ts
ngAfterViewInit() {
const currentUrl = window.location.href;
if (isSignInWithEmailLink(this.authService.auth, currentUrl)) {
const isLoggedIn = !!this.user?.uid;
let email = isLoggedIn
? this.user?.email
: window.localStorage.getItem("emailForSignIn");
if (!email) {
email = window.prompt("Please provide your email for confirmation");
}
if (email && validateEmail(email)) {
try {
// --> important !
if (isLoggedIn) {
const credential = EmailAuthProvider.credentialWithLink(email,currentUrl);
await reauthenticateWithCredential(this.user, credential)
} else {
await signInWithEmailLink(
this.authService.auth,
email,
currentUrl
);
}
window.localStorage.removeItem("emailForSignIn");
this.router.navigateByUrl("/login");
// console.log(userCredential);
} catch (e) {
console.log(e);
// Some error occurred, you can inspect the code: error.code
// Common errors could be invalid email and invalid or expired OTPs.
this.toastr.error(getTranslation(e.code), "Error");
}
} else {
this.toastr.error("Please enter a valid email", "Error");
}
}
}
关于javascript - 无法使用 Firebase 中的电子邮件链接重新进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57664786/