I'm encountering an issue with my NestJS application that uses Passport and JWT for authentication. Initially, everything was working fine, but recently I started receiving the following error when trying to authenticate with a JWT token:
ERROR [ExceptionsHandler] Unknown authentication strategy "jwt"
Error: Unknown authentication strategy "jwt"
at attempt (/path/to/node_modules/passport/lib/middleware/authenticate.js:193:39)
at authenticate (/path/to/node_modules/passport/lib/middleware/authenticate.js:379:7)
...
The issue occurs even though I haven't made changes to the code, and the exact same implementation worked perfectly about two weeks ago. Below are the relevant parts of my code:
Auth Module:
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { CommonModule } from '../common/common.module';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtStrategy } from './strategies/jwt.strategy';
import { UsersService } from './users.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
@Module({
imports: [
ConfigModule,
CommonModule,
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
secret: configService.get('SECRET_KEY'),
signOptions: {
expiresIn: '1d',
},
}),
}),
TypeOrmModule.forFeature([User]),
],
controllers: [AuthController],
providers: [AuthService, UsersService, JwtStrategy],
exports: [PassportModule, JwtStrategy, JwtModule, AuthService],
})
export class AuthModule {}
JWT Strategy:
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { CommonService } from '@/common/common.service';
import { ErrorCodes } from '@/common/interfaces/error-codes.interface';
import { User } from '../entities/user.entity';
import { JwtPayload } from '../interfaces/jwt-payload.interface';
import { UsersService } from '../users.service';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private readonly userService: UsersService,
private readonly configService: ConfigService,
private readonly commonService: CommonService,
) {
super({
secretOrKey: configService.get('SECRET_KEY'),
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
});
}
async validate(payload: JwtPayload): Promise<User> {
const { email } = payload;
const user = await this.userService.findOneByEmail(email);
if (!user) this.commonService.handleErrors(ErrorCodes.TokenNotValid);
delete user.password, user.name, user.email;
return user;
}
}
I am unsure what could be causing this issue since the implementation hasn't changed. Could it be related to dependencies or configurations?
Dependencies:
"@nestjs/passport": "10.0.3"
"@nestjs/jwt": "^10.2.0"
"passport": "^0.7.0"
"passport-jwt": "^4.0.1"
I tried the following steps to resolve the issue:
npm install
to ensure everything is up-to-date.@nestjs/passport
, @nestjs/jwt
, and passport-jwt
packages are installed with compatible versions.I expected the authentication to work as it did before, allowing requests with valid JWT tokens to be processed. However, I continue to receive the error Unknown authentication strategy "jwt", and the requests fail to authenticate.
The error was solved by removing the dependencies of jwt.strategy to commonService and usersService using directly the repository and using the static method of commonService to get the error message, I still don't know why this error happens but the JWT reading is working again.
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { CommonService } from '@/common/common.service';
import { User } from '../entities/user.entity';
import { JwtPayload } from '../interfaces/jwt-payload.interface';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { ErrorCodes } from '@/common/interfaces';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>,
private readonly configService: ConfigService,
) {
super({
secretOrKey: configService.get<string>('SECRET_KEY'),
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
});
}
async validate(payload: JwtPayload): Promise<User> {
const { id } = payload;
const user = await this.userRepository.findOneBy({ id });
if (!user)
throw new UnauthorizedException(
CommonService.getErrorMessage(ErrorCodes.TokenNotValid, 'en'),
);
return user;
}
}