NestJS
Authentication
Implementing authentication in a NestJS application using Passport and JWT.
Install Dependencies: Install Passport, JWT, and their NestJS integrations.
terminal
bash
npm install @nestjs/passport passport @nestjs/jwt passport-jwt
npm install -D @types/passport-jwt
Auth Service: Generate a JWT token upon successful user validation or login.
src/auth/auth.service.ts
typescript
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class AuthService {
constructor(private jwtService: JwtService) {}
async login(user: any) {
const payload = { username: user.username, sub: user.userId };
return {
access_token: this.jwtService.sign(payload),
};
}
}
JWT Strategy: Define a Passport strategy to extract and validate the JWT from incoming requests.
src/auth/jwt.strategy.ts
typescript
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: 'YOUR_SECRET_KEY', // Should be environment variable
});
}
async validate(payload: any) {
return { userId: payload.sub, username: payload.username };
}
}