You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Web端不使用Dynamic Links实现Firebase邮箱链接登录

无需Dynamic Links实现Web平台Firebase邮箱链接登录

需求背景

仅在Web平台使用Firebase邮箱链接认证功能,不依赖Dynamic Links,简化actionCodeSettings配置后寻求正确实现方式。

正确实现步骤

1. 简化actionCodeSettings配置

你的简化思路是对的,移除移动端相关字段和dynamicLinkDomain后,只保留必要的Web端配置即可,注意以下两点:

  • url必须是Firebase控制台已授权的域名地址
  • handleCodeInApp必须设为true(确保链接在应用内处理)

示例配置:

const actionCodeSettings = {
  // 替换为你的授权域名下的回调页面地址
  url: 'https://www.your-domain.com/finish-signup',
  handleCodeInApp: true,
};

2. 发送登录链接给用户

使用Firebase的sendSignInLinkToEmail方法发送链接,同时将用户邮箱存入本地存储,避免后续重复输入:

import { getAuth, sendSignInLinkToEmail } from "firebase/auth";

const auth = getAuth();
const userEmail = document.getElementById('email-input').value; // 从输入框获取用户邮箱

sendSignInLinkToEmail(auth, userEmail, actionCodeSettings)
  .then(() => {
    window.localStorage.setItem('emailForSignIn', userEmail);
    alert('登录链接已发送至你的邮箱,请点击链接完成登录');
  })
  .catch((error) => {
    console.error('发送登录链接失败:', error.code, error.message);
  });

3. 回调页面处理登录逻辑

在url指定的回调页面(比如/finish-signup),需要添加以下代码来验证链接并完成登录:

import { getAuth, isSignInWithEmailLink, signInWithEmailLink } from "firebase/auth";

const auth = getAuth();

// 检查当前URL是否为Firebase登录链接
if (isSignInWithEmailLink(auth, window.location.href)) {
  // 优先从本地存储获取邮箱,若不存在则提示用户输入(跨设备场景)
  let email = window.localStorage.getItem('emailForSignIn');
  if (!email) {
    email = prompt('请输入接收登录链接的邮箱地址');
  }

  if (email) {
    signInWithEmailLink(auth, email, window.location.href)
      .then((userCredential) => {
        // 登录成功,清除本地存储的邮箱
        window.localStorage.removeItem('emailForSignIn');
        // 跳转至应用主页或目标页面
        window.location.href = '/dashboard';
      })
      .catch((error) => {
        console.error('登录验证失败:', error.code, error.message);
      });
  }
}

4. Firebase控制台关键配置

  • 进入Firebase控制台的认证 > 登录方法,确保你的回调域名已添加到授权域名列表中
  • 无需配置Dynamic Links相关选项,因为我们仅针对Web平台实现

内容的提问来源于stack exchange,提问作者Nikhil Bachhav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 14:30:54