Working with PassportJS
Detailed documentation on working with PassportJS library
Steps to Use Passport in NestJS
yarn add @nestjs/passport passport passport-jwtimport { 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<JwtUserPayload> { if (!payload) { throw new UnauthorizedException(); } return payload; } }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 {}import { Injectable } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Injectable() export class JwtAuthenticationGuard extends AuthGuard('jwt') {}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); } }
Key Components:
Google oAuth2Facebook oAuth2
Last updated