Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 677
Tyler Iguchi Avatar asked Jul 09 '15 16:07

Tyler Iguchi


Video Answer


2 Answers

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.

like image 70
Rajiv Ram V Avatar answered Sep 19 '22 13:09

Rajiv Ram V


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

like image 21
Steven Scott Avatar answered Sep 17 '22 13:09

Steven Scott