Strapi with Firebase Auth — Owner’s Policy

Rohan Lamb
3 min readSep 13, 2020

This is a follow up post to a recent one which shows how to integrate Firebase Authentication into Strapi.

What is an owner’s policy & why do you care?

It’s an access control policy which limits the access (READ, WRITE, DELETE) to author/creator of that particular document. Simply put a user can only edit his documents/entries.

As we are implementing our own jwt validation to Strapi, we are basically showing green flag to all the requests which have valid Firebase tokens. It means any authenticated user will be able to read, write & delete any entry regardless of collection or other policies applied from Strapi’s admin panel. This is bad!

Now what?

A lot of fun! We will learn to edit controllers, implement logic to control access and much more. It's IMPORTANT to know that the firebase user that is injected in strapi context has nothing to do with the Strapi’s normal user. Let's get rolling then!

Step 1 — Create a content type for firebase user

We will be storing the firebase user in a separate collection called Firebase Users. A successfully decoded firebase token returns fields like uid, email, phoneNumber. So, we can create a unique field associated to each value as mentioned below.

content type for firebase user

IMPORTANT — Don’t forget to make them unique fields to prevent duplicate entries.

Step 2 — Edit the controller for content type created above

After saving the content type and successful restart you will have a folder for firebase user at path api/firebase-user. This is how the folders inside it will look like

-api/firebase-user
-config
-controllers
-models
-services

Now open controllers/firebase-user.js & paste code from here. Also update extensions/users-permissions/config/policies/permissions.js so that we inject strapi_uid from custom claim setup in controller. Refer permissions.js.

// look for this
if (decodedToken.strapi_uid) {
ctx.state.user.id = decodedToken.strapi_uid;
}

Step 3 — Test it using postman

To test it using postman you need to paste the auth token generated at the time of login in front end. Read more about getting id token.

  • Create User (POST)
  • Get logged in user (GET)

Yay! We have implemented owner's policy for our firebase-user collection. Now you can add relation to firebase-user with any content type and can use it to control access further. Like a blog post have an author relation which will be a firebase-user.

--

--

Rohan Lamb

I am a Full Stack Developer. I love tinkering with computers. I listen music all the time. Love to watch anime.