Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda