【问题标题】:Authentication for firebase hostingFirebase 托管的身份验证
【发布时间】:2018-07-23 01:14:42
【问题描述】:

我有一个托管在 Firebase 主机上的静态应用程序,其后端也在 Firebase 上(使用 firebase JS api 进行通信)。我想在这个网站的所有页面上添加一个简单的身份验证页面,这样只有我想要的用户才能访问这个网站。这可能吗?

查看了文档,但在这方面没有找到任何对我有帮助的东西。

【问题讨论】:

  • @PeterHaddad 我为单个用户开发了这个,但由于它托管在 firebase 上,网络不需要任何注册,只需要一个可用于访问此站点的帐户。跨度>

标签: firebase firebase-realtime-database firebase-authentication firebase-hosting firebase-security


【解决方案1】:

您可以使用 Firebase 函数和 Express 调用来执行此操作。把你所有的静态文件放到一个名为functions/admin的文件夹里,然后把这个函数放到functions/index.js里:

exports.admin = functions.https.onRequest((req, res) => {
  const url = req.originalUrl ? req.originalUrl : '/index.html'  // default to index.html
  res.sendfile('admin' + url)
})

然后,对/admin/* 的函数服务器的请求将提供同名文件。

如果你想添加授权,试试这个:

exports.admin = functions.https.onRequest(async (req, res) => {
  const url = req.originalUrl ? req.originalUrl : '/index.html'
  const user = await get_user(req)  // get the current user
  if (user && user.is_admin)        // is current user an admin?
    res.sendfile('admin' + url)
  else {
    res.status(403).send(null)
  }
})

您必须定义get_user(),以便它返回一个带有is_admin 字段的用户对象。

【讨论】:

  • 你停止解释我猜最重要的部分,身份验证。您能否详细说明如何从 Request 对象中获取当前用户(即使用 get_user(req))?
  • 添加执行身份验证的中间件,可能是这样的:codementor.io/@victornwaiwu/…
【解决方案2】:

这可以通过向您的 Firebase 数据库添加规则来完成,只让经过身份验证的用户进入您可以使用的网站:

// These rules require authentication
{
 "rules": {
   ".read": "auth != null",
   ".write": "auth != null"
 } 
}

你可以用这个:

 {
 "rules": {
   "admin": {
       "$uid": {
          ".write": "$uid === auth.uid"
      }
    }
  }
}

使用上述方法,您将只允许admin 节点下的用户(他们必须经过身份验证)写入数据库,其他人不能。

更多信息在这里:https://firebase.google.com/docs/database/security/

【讨论】:

  • 这是用于 Firebase 数据库,而不是用于托管。
  • @Dimitri OP希望一些用户访问该网站,并且有规则可以做到,甚至第一个答案都说you can use Firebase Authentication plus the server-side security rules (database, storage) of those products to ensure users can only take actions they're authorized for.
【解决方案3】:

Firebase 托管无法限制对您网站的静态资源(HTML、CSS、JavaScript)的访问。见Can Firebase hosting restrict access to resources?Firebase Hosting - Members Only / Secured Webpages?

但如果您的网站提供动态内容(例如 loads data from the Firebase Database from JavaScriptuploads images to Firebase Storage),您可以使用 Firebase 身份验证以及这些产品的服务器端安全规则(databasestorage)来确保用户只能采取他们被授权的行动。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-15
    • 2018-12-05
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多