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.
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:
firebase.json
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();
});
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With