> For the complete documentation index, see [llms.txt](https://intercode.gitbook.io/intercode-saas-kit/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://intercode.gitbook.io/intercode-saas-kit/pages/auth/working-with-passportjs.md).

# Working with PassportJS

[Passport](https://github.com/jaredhanson/passport) is the most popular node.js authentication library, well-known by the community and successfully used in many production applications. It's straightforward to integrate this library with a **Nest** application using the `@nestjs/passport` module

#### Steps to Use Passport in NestJS

1. **Install Dependencies** You'll need to install `@nestjs/passport`, `passport`, and any specific Passport strategies you want to use (e.g., `passport-jwt`, `passport-facebook`, etc.).<br>

   ```bash
   yarn add @nestjs/passport passport passport-jwt
   ```

2. **Create the Strategy** A Passport strategy in NestJS is typically implemented as an injectable service by extending the `PassportStrategy` class from `@nestjs/passport`. You use this class to implement the required strategy.<br>

   **Example: Facebook Strategy for OAuth Authentication**<br>

   <pre class="language-typescript" data-full-width="false"><code class="lang-typescript">import { Injectable, UnauthorizedException } from '@nestjs/common';
   import { PassportStrategy } from '@nestjs/passport';
   import { Strategy, ExtractJwt } from 'passport-jwt';
   import { JwtUserPayload } from 'src/common/interfaces/jwt-user-payload.interface';
   import constants from 'src/constants';

   @Injectable()
   export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
       constructor() {
           super({
               jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
               secretOrKey: constants.TOKEN_SECRET,
           });
       }

       async validate(payload: JwtUserPayload): Promise&#x3C;JwtUserPayload> {
           if (!payload) {
               throw new UnauthorizedException();
           }
           return payload;
       }
   }
   </code></pre>

   \
   Here, `validate` is called when the strategy is triggered, and you check the credentials.<br>

3. **Register the Strategy** In your **Auth Module**, you register the strategy as a provider so that it can be injected and used.<br>

   ```typescript
   import { Module } from '@nestjs/common';
   import { PassportModule } from '@nestjs/passport';
   import { AuthService } from './auth.service';
   import { JwtStrategy } from './jwt-strategy';

   @Module({
     imports: [PassportModule],
     providers: [AuthService, JwtStrategy],
   })
   export class AuthModule {}
   ```

4. **Use the Strategy in a Guard**, you apply Passport strategies using **guards**. NestJS has a built-in `AuthGuard` that integrates with Passport.

   \
   **Example: Facebook Auth Guard**<br>

   ```typescript
   import { Injectable } from '@nestjs/common';
   import { AuthGuard } from '@nestjs/passport';

   @Injectable()
   export class JwtAuthenticationGuard extends AuthGuard('jwt') {}
   ```

   \
   The string `'`jwt`'` refers to the strategy defined in the Facebook`Strategy` class.<br>

5. **Use the Guard in a Controller** Now, you can apply the guard to a route in your controller to protect it using the Passport strategy.<br>

   **Example: Using the JwtAuthGuard in a Controller**<br>

   ```typescript
   typescriptCopy codeimport { Controller, Post, UseGuards, Request } from '@nestjs/common';
   import { AuthService } from './auth.service';
   import { LocalAuthGuard } from './local-auth.guard';

   @Controller('auth')
   export class AuthController {
     constructor(private authService: AuthService) {}

     @UseGuards(JwtAuthenticationGuard)
       @Post('change-team')
       async changeTeam(@Body('teamId') teamId: string, @GetUser() user: JwtUserPayload) {
           return await this.authService.changeTeam(user, teamId);
       }
   }
   ```

   \
   In this case **JwtAuthenticationGuard** will returns us Authenticated user data.

#### Key Components:

1. **Strategy**: Implements a specific authentication mechanism.
2. **Guard**: Applies the strategy to route handlers to protect them.

By using Passport strategies in NestJS, you can easily implement complex authentication mechanisms (like JWT, OAuth, etc.) in a modular and structured way.

***

{% content-ref url="/pages/o9xNoaGdNsCfbbTiD2OI" %}
[Google oAuth2](/intercode-saas-kit/external-integrations/google-oauth2.md)
{% endcontent-ref %}

{% content-ref url="/pages/NrUb92erjzeRNUcgJ9n4" %}
[Facebook oAuth2](/intercode-saas-kit/external-integrations/facebook-oauth2.md)
{% endcontent-ref %}

{% embed url="<https://docs.nestjs.com/recipes/passport>" %}
