Firebase Hosting静态应用全局认证咨询:仅允许指定用户访问
当然可行啦!其实Firebase的工具链完全能帮你实现这个「站点专属访问」的需求,只是可能你没把Auth和Hosting的功能结合起来看~下面给你两种实用方案,按需选就行:
方案一:前端路由拦截(适合纯静态SPA,快速实现)
这种方法不用额外部署后端服务,直接在前端代码里做用户校验,适合对安全性要求不高的个人站点:
- 第一步:先在Firebase控制台的「Authentication」模块,开启邮箱/密码登录方式,然后创建你允许访问的用户(比如你自己的邮箱账号)。
- 第二步:在应用的入口文件(比如
index.js或者SPA的根组件)添加全局认证监听逻辑,拦截未授权的访问:import { getAuth, onAuthStateChanged } from "firebase/auth"; const auth = getAuth(); // 这里放你允许访问的用户邮箱列表 const allowedUsers = ["your-personal-email@example.com", "team-member@example.com"]; onAuthStateChanged(auth, (user) => { const currentPath = window.location.pathname; // 排除登录页面本身,避免无限重定向 if (currentPath !== "/login") { // 如果用户未登录,或者不在允许列表里,跳转到登录页 if (!user || !allowedUsers.includes(user.email)) { window.location.href = "/login"; } } }); - 第三步:创建一个
/login页面,做一个简单的登录表单,调用Firebase Auth的登录接口:import { getAuth, signInWithEmailAndPassword } from "firebase/auth"; const auth = getAuth(); const loginForm = document.getElementById("login-form"); loginForm.addEventListener("submit", (e) => { e.preventDefault(); const email = loginForm.email.value; const password = loginForm.password.value; signInWithEmailAndPassword(auth, email, password) .then(() => { // 登录成功后跳回主页或者之前访问的页面 window.location.href = "/"; }) .catch((error) => { alert(`登录失败:${error.message}`); }); });
方案二:结合Cloud Functions的后端验证(更安全,防止绕过)
前端拦截的方式可能被懂技术的人通过浏览器控制台绕过,如果你的站点需要更高的安全性,推荐用这种后端验证的方式:
- 第一步:同样先在Firebase控制台配置好Auth,创建允许的用户。
- 第二步:写一个Cloud Function用来验证用户的身份令牌,确保只有指定用户能访问:
const functions = require("firebase-functions"); const admin = require("firebase-admin"); admin.initializeApp(); exports.checkSiteAccess = functions.https.onRequest(async (req, res) => { // Firebase Auth会把用户的ID Token存在__session cookie里 const idToken = req.cookies.__session; const allowedUsers = ["your-personal-email@example.com", "team-member@example.com"]; try { // 验证Token的有效性 const decodedToken = await admin.auth().verifyIdToken(idToken); // 检查用户是否在允许列表里 if (allowedUsers.includes(decodedToken.email)) { // 验证通过,放行到原页面 res.status(200).send("Authenticated"); } else { // 不在列表里,跳转到登录页 res.redirect("/login"); } } catch (error) { // 没有有效Token,跳转到登录页 res.redirect("/login"); } }); - 第三步:修改
firebase.json的Hosting配置,让所有页面请求先经过这个Function验证(排除登录页和静态资源):{ "hosting": { "public": "dist", // 你的静态资源目录 "rewrites": [ { "source": "**", "function": "checkSiteAccess", "exclude": ["/login", "/static/**"] }, { "source": "**", "destination": "/index.html" // SPA应用的 fallback 规则 } ] } } - 第四步:部署这个Cloud Function,然后重新部署Hosting配置即可。
额外小提示
- 如果你不想用邮箱密码,也可以用Google登录、GitHub登录等方式,只要在允许列表里对应填写用户的邮箱就行;
- 前端拦截方案可以配合Firebase Auth的持久化登录,让用户不用每次访问都重新登录;
- 后端验证方案里,Firebase Web SDK默认会自动处理会话Cookie的存储,不用额外配置。
内容的提问来源于stack exchange,提问作者ayushgp
相关产品推荐
相关产品推荐

