mikenicholson / passport-jwt

Passport authentication using JSON Web Tokens
MIT License
1.96k stars 213 forks source link

"TypeError: JwtStrategy requires a secret or key" with NestJS #227

Open huss-a opened 3 years ago

huss-a commented 3 years ago

I'm getting a TypeError: JwtStrategy requires a secret or key error in a NestJS application, here's the code

// auth.module.ts (AuthModule)

import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersRepo } from './users.repository';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy } from './jwt.strategy';

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secret: 'keyboard-cat',
      signOptions: {
        expiresIn: 3600,
      },
    }),
    TypeOrmModule.forFeature([UsersRepo]),
  ],
  providers: [AuthService, JwtStrategy],
  controllers: [AuthController],
  exports: [JwtStrategy, PassportModule],
})
export class AuthModule {}
// jwt.strategy.ts
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { validate } from 'class-validator';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { jwtPayload } from './jwt-payload.interface';
import { UsersRepo } from './users.repository';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(@InjectRepository(UsersRepo) private usersRepo: UsersRepo) {
    super({
      secret: 'keyboard-cat',
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    });
  }
}
VividLemon commented 2 years ago

Pretty sure the "secret" in your constructor and jwtmodule.register need to be "secretOrKey"

Outternet commented 1 year ago

@VividLemon this is not correct @nestjs/jwt does accept the secret param, the passport-jwt library on the other side does not and this should be replaced with secretOrKey.

neoligero commented 1 year ago

Im having the same issue. I even try to hardcode the secret string, for discard environment issues. And the result is :

[Nest] 46027 - 05/20/2023, 10:30:27 PM ERROR [ExceptionsHandler] secretOrPrivateKey must have a value Error: secretOrPrivateKey must have a value

I dont know what else do

LabuPaim commented 1 year ago

I believe your .env has to have a SECRET_KEY=""

aperacaula commented 1 year ago

@neoligero same thing here… I am really struggling and don’t understand why not even hardcoding it I get rid of the ffff error, I m desperate. Did you solve it?

Caique-LF commented 6 days ago

Guys, I also had the error, but I still can't solve it, did you have any success?

Caique-LF commented 6 days ago

Guys, in my case the error was resolved when I imported dotenv directly into main.ts. From what I understand in the Linux environment this needs to be done. the error is not in stategy or guards.

import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
import { ValidationPipe } from '@nestjs/common'
import * as dotenv from 'dotenv'

dotenv.config()

async function bootstrap() {
console.log('JWT_SECRET:', process.env.JWT_SECRET)
const app = await NestFactory.create(AppModule)
app.useGlobalPipes(new ValidationPipe())
await app.listen(3000)
}
bootstrap()