authenticationjwtnestjspassport-jwt

Validating a token in Jwt strategy


I'm trying to validate a token but the validate function is not called from my token Strategy file and returns a 401 status code, here are my Auth module and my tokenStrategy:

import { Module } from "@nestjs/common";
import { AuthDashboardDesarrolloController } from "./auth-dashboard-desarrollo.controller";
import { AuthDashboardDesarrolloService } from "./auth-dashboard-desarrollo.service";
import { MailService } from "@enlazo/mail/dist/mail.service";
import { DatabaseModule } from "@enlazo/bd_ibm/dist";
import { MailModule } from "@enlazo/mail/dist";
import { APP_FILTER } from "@nestjs/core";
import { HttpExceptionFilter } from "@enlazo/nestjscommon/dist/filters";
import { JwtService, JwtModule } from "@nestjs/jwt";
import { PassportModule } from '@nestjs/passport';
import { ConfigModule } from '@nestjs/config';
import { TokenStrategy } from './strategy/tokenStrategy'

@Module({
    imports: [DatabaseModule, MailModule, JwtModule.register({ secret:'secret' }), PassportModule],
    controllers: [AuthDashboardDesarrolloController],
    providers: [
        AuthDashboardDesarrolloService,
        MailService,
        JwtService,
        TokenStrategy,
        AuthDashboardDesarrolloService,
        //JwtStrategy,
        {
            provide: APP_FILTER,
            useClass: HttpExceptionFilter
        }
    ]
})
export class AuthDashboardDesarrolloModule {}

and here is my strategy:

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { JwtPayload } from '../type/payload';

@Injectable()
export class TokenStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer'),
      secretOrKey: 'secret',
    });    
  }

  validate(payload: JwtPayload) {
    return payload;
  }
} 

Solution

  • The secret or key must be the same of the source you get the token