Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
huss-a opened this issue Jun 13, 2021 · 9 comments
Open

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

huss-a opened this issue Jun 13, 2021 · 9 comments

Comments

@huss-a
Copy link

huss-a commented Jun 13, 2021

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
Copy link

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

@Outternet
Copy link

@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
Copy link

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
Copy link

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

@aperacaula
Copy link

@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
Copy link

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

@Caique-LF
Copy link

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()

@hoangdaochuz
Copy link

hoangdaochuz commented Sep 1, 2024

@Caique-LF Yeah, you're right, I solved the issue following what you say. Thanks

@bed-com-52-20
Copy link

In my case, I was using @nestjs/config and solved the isuue by indicating the file path of .env file when registering the ConfigModule as follows: ConfigModule.forRoot({isGlobal: true, envFilePath: 'C:/Users/me/Desktop/project/backend/src/.env'}) You can also use the relative path instead of the long one I have provided.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

9 participants