2

I'm trying to use jwt in nest Everything is ok, but validate function is not working in jwt.strategy.ts

this is my jwt.strategy.ts:

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
     private userService:UserService
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey:"mysecretkey",
    });
  }

  async validate(payload:any) {
      console.log('this is payload'+payload)

it prints: this is payload undefine

user.modul

@Module({
  exports:[UserService],
  controllers: [UserController],
  providers: [UserService,JwtStrategy],
  imports : [TypeOrmModule.forFeature([UserEntity]),PassportModule.register(
    {defaultStrategy:'jwt'}),
  JwtModule.register({secret:'mysecretkey',signOptions:{expiresIn:3600000}})]
})
export class UserModule {}

When i request in postman, i get satus:401 Unauthorized and in termenal show : payload undefined

Med
  • 73
  • 9

2 Answers2

1

If you haven't already, then you have to define the JwtAuthGuard class which extends the built-in AuthGuard.

//jwt-auth.guard.ts
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}

Then, you can implement protected route and its associated Guard. Like,

@UseGuards(JwtAuthGuard)
  @Get('profile')
  getProfile(@Request() req) {
    return req.user;
  }

Refer Nestjs docs


EDIT:

You need to generate userToken everytime you create a new user. Return this userToken in response of CreateUser API which can be used by the frontend. Also, the userToken generated should be used in API requests wherever needed.

Inject this AuthService in your UserService class and call this method to generate jwt token.

import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(private readonly jwtService: JwtService) {}

  getJwtToken(userId: number, phone: string) {
    const payload = { userId: userId, userPhone: phone }; //Set whatever data you need to keep in your jwt
    return this.jwtService.sign(payload);
  }
}

Rasool Khan
  • 413
  • 6
  • 15
0

I was getting this error too. In my case I use such secretOrKey: process.env.PRIVATE_KEY || 'SECRET'

And I found that in JwtStrategy (that extends PassportStrategy(Strategy)) was used process.env.PRIVATE_KEY, but on auth module in JwtModule.register({secret: process.env.PRIVATE_KEY || 'SECRET', ...}) was used 'SECRET'!

Check you secret key.