Restrict Access to Static Resources Using Firebase
At JoyLabs we wanted to deploy a Jekyll site, but only allow authenticated users access to it.
GitHub Pages is a very convenient way to deploy Jekyll-based static sites, but, unfortunately,
it’s impossible to restrict access to only authenticated users.
After some research, it seemed that Firebase would provide us everything we need:
Static file hosting
Authentication
Cloud functions
Unfortunately, out of the box, Firebase doesn’t support content restriction to authenticated users. However, with a simple cloud function,
we can do just that.
Let’s start with creation of the Firebase project. To create a new Firebase project, visit the Firebase Console and add a new project.
Then, inside the project, visit the Hosting section and follow instructions to install firebase-tools
Select Functions and Hosting:
Now, let’s try to make a test deploy:
Next, visit our test site. Nice! Our site is deployed, but it’s wide open to the public.
Let’s add authentication, now. Luckily, Firebase supports authentication out of the box, so we can let users authenticate on our site easily. To enable authentication on a Firebase-hosted site, visit the Authentication
section in the firebase console and set up a sign-in method. For now, just enable the Google authentication provider, then click Web Setup
in top right corner and get firebase JavaScript config:
Create a login.html page under the public directory and put firebase init scripts there. Now we can trigger google authentication:
This code will let us retrieve an ID Token, which we can decode and verify in our cloud function (that we have yet to write).
Before moving on, let’s check that our login pop-up works, visiting https://fir-auth-example-a4f18.firebaseapp.com/login.html (don’t forget to deploy the site first).
Now we are able to authenticate a user, but everything is still publicly accessible. Our workaround is to have only login.html
deployed to be accessible to everyone
and serve everything else from GCS, using cloud function as a proxy that will also check if the user is authenticated.
Let’s move everything except login.html to new folder content. We will upload this folder to private GCS bucket,
not accessible to the outside world. We have to redirect all requests to our cloud function in firebase.json:
Now, copy our hidden content to GCS bucket:
And create our proxy cloud function functions/index.js:
Now we can firebase deploy our site and, voilà!; our static website is protected
with google authentication (pop-ups have to be enabled for authentication to work; however, firebase also supports inline authentication widget).
All code on this page is provided for illustrative purposes only. These examples have not been thoroughly tested under all conditions. JoyLabs cannot guarantee or imply reliability, serviceability, or function of these programs.