NestJs: Firebase Auth secured NestJs app
NestJs is an excellent framework on NodeJs written in TypeScript and/or JavaScript. Its efficiency and scalability enable you to create a range of varied application backends. This makes it very important to have a rigid security mechanism in your apps.
This post will help you secure your NestJs APIs through Firebase Auth.
Step#1: Create a Firebase project and add a web app.
Follow the steps here.
Step#2: Create a NestJs project.
I prefer to use Nest CLI for the same. If you do not have Nest CLI, download the package through NPM using the command:
$ npm install -g @nestjs/cli
To create a NestJs app (I am naming my project ‘firebase-auth’; give any name of your choice), open a console in your preferred folder, and run the command:
$ nest new firebase-auth
Step#3: Install firebase dependencies
Console inside your new project and add the ‘firebase-admin’ package to the project.
$ npm install — save firebase-admin
Step#4: Create a firebase service account
Create a service account in the firebase console and download the service account JSON file. Follow the steps here.
Step#5: Download the service account JSON in the project
Open the project in your favorite IDE. Create a folder, say ‘auth’ inside src. Copy the service account JSON file in this folder.
Step#6: Allow resolveJsonModule
Set “resolveJsonModule”: true in your tsconfig.json file. This is to allow importing JSON files in Typescript.
Step#7: Create auth middleware
Create a NestJs middleware inside the auth folder, say ‘preauth.middlewate.ts’. Create a constant JSON object using the service account JSON. Import the firebase-admin SDK and initialize using the constant JSON.
Step#8: Verify the firebase bearer token
Alter the ‘use’ method inside the middleware to read Bearer token from the request and use firebase-admin to verify the token. Finally, set an object containing the user’s email to the request object.
Note: @ Line#33, I am not securing requests without authorization header.
Step#9: Register the middleware
Register the middleware in the root module for all requests.
Step#10: Create a controller to verify.
Step#11: Run & Verify failure scenario
$ npm run dev
Step#12: Create a firebase user and verify success scenario
For a success flow, create any client to accept firebase login and obtain a valid firebase idToken. Use this token as a Bearer token in the Authorization header.
Codebase:
https://github.com/sharmavikashkr/firebase-auth-nestjs
Firebase auth in NestJs using PassportJs -> here.