Is it possible to require a password to access a site hosted on firebase?

百般思念 提交于 2019-11-27 20:45:49

问题


I'm hosting a site using firebase and want to be able to prevent people from accessing it, tried using a .htaccess file, wondering if anyone has been able to do it before.


回答1:


Here is a little hack that simulates HTTP Basic authentication using firebase cloud functions and a little rearrangement of files.

There are 3 steps to this:

  1. Set up the necessary cloud function
  2. Move the files you want to protect into a "secret" folder
  3. Update your firebase.json

1. Cloud Function

const USERNAME = 'USERNAME'
const PASSWORD = 'PASSWORD' 
const denyAccess = (res) => {
  res.statusCode = 401;
  res.setHeader('WWW-Authenticate', 'Basic realm="Authorization 
  Required');
  res.end('Unauthorized');
}

exports.authorizeAccess = functions.https.onRequest((req, res) => {
  if (typeof req.headers.authorization !== 'string') {
    denyAccess(res);
    return;
  }

  const base64Auth = req.headers.authorization.split(' ')[1];
  if (typeof base64Auth !== 'string' ) {
   denyAccess(res);
   return;
  }

  const [user, pass] = Buffer.from(base64Auth, 
  'base64').toString().split(':');
  if (user !== USERNAME || pass !== PASSWORD) {
    denyAccess(res);
    return;
  }

  const urlObject = url.parse(req.url);
  urlObject.pathname = 
  `/${PASSWORD}${urlObject.pathname}`;
  const location = url.format(urlObject);

  res.writeHead(302, { location });
  res.end();
});

2. Move files into secret folder

Suppose the folder that you have set as public in firebase.json looks like this:

.
├── index.html
├── js
|   ├── main.js
|   └── main.js.map
└── styles.css

then make it look like this

.
└── PASSWORD
    ├── index.html
    ├── js
    |   ├── main.js
    |   └── main.js.map
    └── styles.css

3. firebase.json

{
  ...
  "rewrites": {
    "source": "/"
    "function": "authorizeAccess"
  }
  ...
}

We had to password protect our source maps in production; we had to have them in there in the first place so that Sentry would pick it up. Our build scripts would take care of moving the files into the necessary folder.




回答2:


If you are hosting a site, and want to access firebase data on your site, you can add authentication to your application to control who can change or view data. According to the manual: Firebase Authentication



来源:https://stackoverflow.com/questions/31323630/is-it-possible-to-require-a-password-to-access-a-site-hosted-on-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!