Passport (Authentication)
Strategy
Implement the strategy logic based on using existing strategy (e.g :
passport-local,passport-jwt)
@Module({
imports: [
PassportModule,
// if implementing jwt strategy
JwtModule.register({
secret: jwtConstants.secret,
signOptions: { expiresIn: '60s' },
}),
],
controllers: [AuthController],
exports: [AuthService],
providers: [AuthService, StaartStrategy],
})
export class AuthModule {}Example 1
import { Injectable, Logger } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Request } from 'express';
import { Strategy } from 'passport-strategy';
import { AuthService } from './auth.service';
class StaartStrategyName extends PassportStrategy(Strategy) {
name = 'staart';
}
@Injectable()
export class StaartStrategy extends PassportStrategy(StaartStrategyName) {
constructor(
private authService: AuthService,
) {
super();
}
private safeSuccess(result: AccessTokenParsed) {
return this.success(result);
}
async authenticate(request: Request) {
return this.success(result);
return this.fail('Invalid token', 401);
}
}Example 2
Guard
Declare the guard of using strategy
Declare the public decorator
Apply the auth guard on global level
Last updated
Was this helpful?