Secure Your NestJS Application with Firebase Authentication

Why Authentication Matters

Authentication is a crucial aspect of any application, but it can be a daunting task to set up from scratch. Fortunately, Firebase provides a comprehensive solution to simplify the process. In this article, we’ll explore how to integrate Firebase Authentication into a NestJS application, ensuring that only authorized users can access restricted resources.

What is Firebase?

Firebase is a suite of products and solutions designed to make application development easier. It offers a range of services, including databases, authentication, analytics, and hosting. With Firebase, you can focus on building your application without worrying about the underlying infrastructure.

Getting Started with Firebase

To begin, create a Firebase application, which will provide you with the necessary configurations for your NestJS application. Follow these steps:

  1. Go to the Firebase console and click on “Add Project.”
  2. Name your project and disable Google Analytics if you don’t need it.
  3. Click on “Create Project” and then navigate to the “Project Settings” menu.
  4. Under the “Service Accounts” tab, generate a new private key, which will download a JSON file with credentials for initializing the Firebase Admin SDK on the server side.
  5. In the same “Project Settings” menu, register your application with Firebase under the “General” tab.
  6. Enable Email/Password authentication under the “Sign-in method” menu.

Initializing Your NestJS Application

Next, install the Nest CLI package globally, which will provide you with commands for bootstrapping a new NestJS application. Run the following command:

npm install -g @nestjs/cli

Then, create a new NestJS project using the following command:

nest new my-nest-app

Setting Up Firebase Authentication

To authenticate users from the client side with Firebase, initialize your application using the Firebase web configuration provided in the Firebase console. Add the settings to your main.js file in the public folder.

Creating Routes and HBS Files

Create routes for login and signup, and add the corresponding HBS files. In the app.controller.ts file, add the following code:

“`typescript
import { Controller, Get } from ‘@nestjs/common’;

@Controller()
export class AppController {
@Get(‘login’)
login() {
return ‘login.hbs’;
}

@Get(‘signup’)
signup() {
return ‘ignup.hbs’;
}
}
“`

Creating a Restricted Resource

Create a new resource folder with a module, controller, and service. In the resources.service.ts file, add the following code:

“`typescript
import { Injectable } from ‘@nestjs/common’;

@Injectable()
export class ResourcesService {
private quotes = [
{ quote: ‘Eat my shorts!’, author: ‘Bart Simpson’ },
{ quote: ‘D’oh!’, author: ‘Homer Simpson’ },
//…
];

getAll() {
return this.quotes;
}
}
“`

Integrating Firebase-Admin

To verify the JWT token sent from the client, create a Passport strategy for Firebase. In the firebase-auth.strategy.ts file, add the following code:

“`typescript
import { Injectable } from ‘@nestjs/common’;
import * as admin from ‘firebase-admin’;

@Injectable()
export class FirebaseAuthStrategy {
async validate(token: string) {
try {
const decodedToken = await admin.auth().verifyIdToken(token);
return decodedToken;
} catch (error) {
throw new UnauthorizedException();
}
}
}
“`

Protecting Your Resource

Create a guard to make use of the Firebase strategy, and update your resources.controller.ts file to use the guard:

“`typescript
import { Controller, Get } from ‘@nestjs/common’;
import { FirebaseAuthGuard } from ‘./firebase-auth.guard’;

@Controller(‘resources’)
export class ResourcesController {
@Get()
@UseGuards(FirebaseAuthGuard)
async getAll() {
return this.resourcesService.getAll();
}
}
“`

With these steps, you’ve successfully integrated Firebase Authentication into your NestJS application, ensuring that only authorized users can access restricted resources.

Leave a Reply

Your email address will not be published. Required fields are marked *