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

Firebase Authentication在127.0.0.1失效但localhost可用问题求助

Firebase Authentication在127.0.0.1下失效但localhost正常的问题分析与解决

问题场景

使用Firebase Authentication时,以127.0.0.1作为主机访问项目,认证功能完全无法工作;但切换到localhost后,登录、登出一切正常。相关代码如下:

<!DOCTYPE html>
<html>

<body>
    <button id="btn1">Log in/Sign up</button>
    <button id="btn2" disabled>Sign Out</button>

    <script type="module">

        import { initializeApp } from "https://www.gstatic.com/firebasejs/10.9.0/firebase-app.js"
        import { getAuth, GoogleAuthProvider, signInWithPopup, signOut} from "https://www.gstatic.com/firebasejs/10.9.0/firebase-auth.js"
        const firebaseConfig = {
            // my config
        }

        const app = initializeApp(firebaseConfig)
        const auth = getAuth()
        const provider = new GoogleAuthProvider()

        async function SignIn() {
            await signInWithPopup(auth, provider)

            btn1.disabled = true
            btn2.disabled = false
        }

        async function SignOut() {
            await signOut(auth)

            btn1.disabled = false
            btn2.disabled = true
        }

        btn1.addEventListener('click', SignIn)
        btn2.addEventListener('click', SignOut)

    </script>
</body>

</html>

核心原因

Firebase Authentication会严格校验请求来源的域名,127.0.0.1和localhost在Firebase的授权规则里是两个完全独立的域名,默认情况下控制台的授权域列表里只会包含localhost,不会自动添加127.0.0.1,因此用127.0.0.1访问时,请求会被Firebase的安全策略拦截。

另外,浏览器会将127.0.0.1和localhost视为不同的源,Firebase认证依赖的会话Cookie可能无法在127.0.0.1域名下正常存储或读取,导致认证流程中断。

解决步骤

  1. 添加127.0.0.1到Firebase授权域

    • 登录Firebase控制台,进入你的项目
    • 左侧菜单选择「Authentication」,切换到「设置」标签页
    • 找到「授权域」区域,点击「添加域」
    • 输入你的127.0.0.1地址(如果项目使用了自定义端口,比如5500,要完整输入http://127.0.0.1:5500)
    • 保存设置,等待1-2分钟让配置生效后重新测试
  2. 确保端口一致
    如果你的本地服务器使用了非默认端口,要保证授权域中添加的127.0.0.1地址端口和服务器运行的端口完全匹配,否则依然会被拦截。

  3. 清理浏览器缓存
    部分情况下浏览器缓存的旧认证数据会干扰新配置的生效,建议清除当前域名的Cookie和缓存后,重新打开页面测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 00:42:49