React项目使用Firebase邮箱密码登录时遇跨域重定向登录不支持错误
我正在使用React.js开发一款Web应用,采用Firebase的邮箱/密码登录方式,但遇到错误导致无法存储用户ID/密码,我认为这主要是CORS相关问题。
我已尝试YouTube、StackOverflow上的解决方案,也查阅了Firebase官方文档,但未能理解并解决问题,已卡两周,恳请帮助。
抛出的错误信息
Google Chrome M115+ 不再支持跨源重定向登录,该功能将于2024年6月24日停止工作。
请在2024年6月24日前迁移到替代解决方案
终端用户在2024年6月24日前仍可登录你的应用
Firefox 109+ 和 Safari 16.1+ 已要求采用替代方案
相关代码
Firebase配置代码
// Import the functions you need from the SDKs you need import { initializeApp } from "firebase/app"; import { getAnalytics } from "firebase/analytics"; import { getAuth } from "firebase/auth"; // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries // Your web app's Firebase configuration // For Firebase JS SDK v7.20.0 and later, measurementId is optional, // 已隐藏个人ID和数据 const firebaseConfig = { apiKey: "AIzaSyDw6105zrb-IhlcZxDa****************", authDomain: "netlfix-gpt******.web.app", projectId: "netlfix-gpt******", storageBucket: "netlfix-gpt*******.appspot.com", messagingSenderId: "9065506*******", appId: "1:906550651177:web:***************", measurementId: "G-HQ********" }; // Initialize Firebase const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); export const auth= getAuth();
firebase.json文件代码
{ "hosting": { "public": "build", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ] } }
.firebaserc文件代码
{ "projects": { "default": "netlfix-gpt-*****" } }
这个错误并非传统CORS问题,是浏览器对跨源重定向登录的限制导致的,针对邮箱/密码登录场景,按以下步骤修复:
确认登录实现逻辑
确保使用Firebase Auth的signInWithEmailAndPassword方法完成登录,邮箱密码登录本身无需重定向,若误用第三方登录的重定向逻辑,会触发该错误。检查认证域配置
登录Firebase控制台,进入项目→认证→设置→授权域,确认应用部署域名(含本地开发的localhost:端口号)已添加至列表。更新Firebase SDK版本
执行npm install firebase@latest更新至最新SDK版本,旧版本可能存在适配问题。本地开发规范
本地开发时不要用file://协议打开页面,必须通过localhost服务器(比如React默认npm start启动的http://localhost:3000)访问,避免触发跨源限制。移除自定义重定向
不要手动给登录流程添加跨域重定向,Firebase Auth的邮箱密码登录是纯前端完成的,无需跳转至其他域名。
内容的提问来源于stack exchange,提问作者Vineet Raj

