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

Firebase Web电话认证:如何将idToken传递至重定向URL

如何将Firebase电话认证的idToken传递到重定向URL

我来帮你搞定这个问题!你遇到的情况是用原生Firebase Auth SDK做电话认证,想要把生成的idToken带到重定向URL里——其实核心就是在认证成功的回调里获取idToken,再用它构造跳转链接,你之前看的那个链接是针对Firebase UI的方案,和你用的原生SDK逻辑不一样,所以对你的代码不适用。

具体修改思路

你需要在confirmationResult.confirm()的成功回调里,先拿到认证后的用户对象,再调用getIdToken()获取token,最后用这个token拼出目标跳转URL并完成页面跳转。

修改后的完整代码

<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <title> Firebase Phone Number Auth </title> 
</head> 
<body> 
  <form> 
    <input type="text" id="verificationcode" placeholder="enter verification code">
    <input type="button" value="Submit" onclick="myFunction()"> 
  </form> 
  <div id="recaptcha-container"></div> 

  <script src="https://www.gstatic.com/firebasejs/4.8.1/firebase.js"></script> 
  <script> 
    // Initialize Firebase 
    var config = { 
      apiKey: "*******************", 
      authDomain: "*******.firebaseapp.com", 
      databaseURL: "https://*******.firebaseio.com", 
      projectId: "*******", 
      storageBucket: "*******.appspot.com", 
      messagingSenderId: "*******" 
    }; 
    firebase.initializeApp(config); 
  </script> 

  <script type="text/javascript"> 
    window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container', { 
      'size': 'invisible', 
      'callback': function (response) { 
        onSignInSubmit(); 
      } 
    }); 

    firebase.auth().signInWithPhoneNumber("+1(111) 111-1111", window.recaptchaVerifier) 
      .then(function (confirmationResult) { 
        window.confirmationResult = confirmationResult; 
      }); 

    var myFunction = function () { 
      window.confirmationResult.confirm(document.getElementById("verificationcode").value) 
        .then(function (result) { 
          // 获取认证成功后的用户对象
          const user = result.user;
          // 异步获取idToken
          user.getIdToken().then(function(idToken) {
            // 构造带token的重定向URL,替换成你的目标地址
            const redirectUrl = `http://example.com/?token=${idToken}`;
            // 跳转到目标页面
            window.location.href = redirectUrl;
          }).catch(function(error) {
            // 处理获取token失败的异常
            alert('获取Token失败:' + error.message);
          });
        }, function (error) { 
          alert('认证失败:' + error.message); 
        }); 
    }; 
  </script> 
</body> 
</html>

关键细节说明

  1. 获取idToken:认证成功后,result.user就是当前登录的用户实例,调用user.getIdToken()可以异步获取到有效的idToken。
  2. 构造跳转链接:用模板字符串把token拼接到目标URL的查询参数中,再通过window.location.href完成页面跳转。
  3. 异常处理:添加了获取token失败的捕获逻辑,避免出现无提示的静默错误,提升用户体验。

额外注意事项

  • 如果你需要在目标页面验证idToken的合法性,后端要使用Firebase Admin SDK调用verifyIdToken接口来校验token的有效性。
  • idToken默认有效期为1小时,如果需要长期维持登录状态,后端要处理刷新token的逻辑。
  • 建议使用HTTPS协议传输,避免token在网络传输过程中被明文窃取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:04:32