Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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

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);
                in userService i implement methede findUserByEmail in validate i need to use this method for get informations about user from database
– Med 
                Sep 21, 2021 at 12:26

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.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.