Firebase 托管的身份验证 [英] Authentication for firebase hosting

本文介绍了Firebase 托管的身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a static app hosted on Firebase hosting whose backend is also on Firebase(communicating using firebase JS api). I want to add a simple auth page to all pages of this website so that only users I want can access this site. Is this possible?

查看了文档,但在这方面没有找到任何对我有帮助的内容.

Looked at the docs but didn't find anything that helps me in this regard.

推荐答案

您可以使用 Firebase 函数和 Express 调用来执行此操作.将所有静态文件放入名为 functions/admin 的文件夹中,并将此函数放入 functions/index.js:

You can do this using Firebase Functions, and an Express call. Put all of your static files into a folder named functions/admin and put this function into 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/* 的函数服务器的请求将提供同名文件.

Then, a request to your functions server for /admin/* will serve up the file of the same name.

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

If you want to add authorization, try this:

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 字段的用户对象.

You will have to define get_user() so it returns a user object with an is_admin field.

这篇关于Firebase 托管的身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆