Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

201
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!