Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

195
Vistas
Trouble with authorization in NestJS using jwt and passport

I have a ruby on rails api that will connect to a nestjs api that i'm making from scratch. I will create a jwt token on rails and use it as the authorization, using the same signature on both projects. For now, i'm testing only via postman calling the NestJS api, but it is returning "UNAUTHORIZED" on every request. Here's a little bit of my code:

jwt.doctor.strategy.ts

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

@Injectable({})
export class JwtDoctorStrategy extends PassportStrategy(
  Strategy,
  'jwt.doctor',
) {
  constructor(config: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: config.get('JWT_DOCTOR_SECRET'),
    });
  }

  validate(payload: any) {
    console.log({
      payload,
    });

    return payload;
  }
}

PS: i created two strategies because i have different signatures for different cases. The other one is very similar to this one, but for now i'm only tested the one i provided above.

doctor.controller.ts

import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller('doctors')
export class DoctorController {
  @UseGuards(AuthGuard('jwt.doctor'))
  @Get('me')
  getMe() {
    return 'User info';
  }
}

Am i missing something? I'm creating the jwt token in the console for test purposes, and its being validated ok on the jwt website. Would appreciate very much any insights (:

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

We can pass an options object in the call to super() to customize the behavior of the passport strategy. In this example, the passport-local strategy by default expects properties called username and password in the request body. Pass an options object to specify different property names, for example: super({ usernameField: 'email' })

import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { jwtConstants } from './constants';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
       usernameField: 'email' // your strategy here in super
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
    });
  }

  async validate(payload: any) {
    return { userId: payload.sub, email: payload.email };
  }
}

Also assuming that your other Modules are importing the AuthModule in order to have access to the AuthService you could just re-export the PassportModule:

const passportModule = PassportModule.register({ defaultStrategy: 'jwt' });

@Module({
  imports: [
    passportModule,
    JwtModule.register({
      secretOrPrivateKey: 'secretKey',
      signOptions: {
        expiresIn: 3600,
      },
    }),
    UsersModule,
  ],
  providers: [AuthService, JwtStrategy],
  exports: [passportModule]
})
export class AuthModule {}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda