Restrict access to Firebase Hosting content

Viewed 348

I'm building a set of rest APIs on firebase. I've generated docs with both swagger (for "external" docs) and jsdoc (for "internal" ones). Hence, from jsdoc, I have a bunch of HTML pages that I want to deploy onto FB hosting, but I want to restrict access to such pages only to some authenticated users.

For dynamic content, e.g. swagger-generated, I've easily solved as follows.

doc_fun.use(
  '/rest',
  basicAuth({
    users: {'user': 'password'},
    challenge: true,
  }),
  swaggerUi.serve,
  swaggerUi.setup(swaggerSpec)
)
exports.docs = functions.https.onRequest(doc_fun)

I'm looking for (possibly similar) solution for static content. Something like:

doc_fun.use(
  '/jsdoc', 
  basicAuth({
    users: {'user': 'password'},
    challenge: true,
  }), 
  express.static('public/jsdoc')
)

(which, of course, doesn't work)

2 Answers

You will find everything you need in this official Cloud Functions sample, which shows "how to authenticate access to a JSON API to only allow access to data for a specific Firebase user".

More precisely, it shows how the Express middleware "validates Firebase ID Tokens passed in the Authorization HTTP header".

Inspired by the last comment by Renaud, I've managed to find a simple workaround.

I post it here so that, maybe, it can be useful to someone else.

  • I put my 'jsdoc' folder with all its HTML static content inside 'functions' one
  • I've set express.static path parameter to './jsdoc'

index.js:

doc_fun.use(
  '/jsdoc', 
   basicAuth({
     users: {'user': 'password'},
     challenge: true,
   }), 
   express.static('./jsdoc') //current folder is 'functions'
 )

firebase.json:

...,
"rewrites": [
  ...,
  {
    "source": "/docs/**",
    "function": "docs"
  }
],
...

And now http://my_project.cloudfunctions.net/docs/jsdoc/ is serving my static content only to authenticated visitors.

Related