#Validating Jwt

1 messages · Page 1 of 1 (latest)

loud shard
#

I'm trying to validate a token but the validate function is not called form my token Strategy 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:'Dashboard' }), 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('Enlazo'),
      secretOrKey: 'Dashboard',
    });    
  }

  validate(payload: JwtPayload) {
    console.log('hola')
    return payload;
  }
}
frail gorgeBOT
#

Please format your question or answer with Markdown formatting.
It leads to better readability and an easier time to spot problems.
For code blocks, you can wrap your block with three back ticks before and after the block, and after the first three back ticks you can add a language (like ts) to add syntax highlighting.
e.g.

```ts
@Injectable()
export class MySuperAwesomeService {
constructor(@Inject('InjectionToken') private readonly dep: SomeDependency) {}

getRandomNumber(): number {
return Math.round(Math.random() * 1000);
}
}
```

Becomes :point_down:

@Injectable()
export class MySuperAwesomeService {
  constructor(@Inject('InjectionToken') private readonly dep: SomeDependency) {}

  getRandomNumber(): number {
    return Math.round(Math.random() * 1000);
  }
}
fiery karma
#

In your AuthGuard, try adding this:

handleRequest(...args: Parameters<InstanceType<ReturnType<typeof AuthGuard>>['handleRequest']>) {
  console.log(args);
  return super.handleRequest(...args);
}

It won't immediately fix anything, but it will give you some debug logs to work with

loud shard
fiery karma
#

Do you have the AT_SECRET defined in production?

loud shard
#

yes

#

and updated the env file

#

I've seen that you could write you env variable in CI/CD like this -> - echo "AT_SECRET=$AT_SECRET" >> .env
that could do?

fiery karma
#

That would just set the value inside the .env in the CI/CD pipeline

#

With your production environment, how do you set env variables? What is production for you, cause you said that's where it isn't working

loud shard
#

I have a script that deploy it with pm2 ->
stages: # List of stages for jobs, and their order of execution

  • pull
  • build
  • run

variables:
GIT_STRATEGY: none

pull-job:
stage: pull
only:
- master
tags:
- nodejs
script:
- cd /opt/dashboardnestjs/
- git pull

build-job:
stage: build
only:
- master
tags:
- nodejs
script:
- cd /opt/dashboardnestjs/
- npm install

run-job:
stage: run
only:
- master
tags:
- nodejs
script:
- cd /opt/dashboardnestjs/
- npm run build
- pm2 restart Dashboard

#

then the env variables are written ecosystem.config.js file like this

#

module.exports = {
apps : [
{
name: "Dashboard",
script: '/opt/dashboardnestjs/dist/main.js',
env: {
"NODE_ENV": "",
"PORT": ,
"DB_CONNECTION":"",
"DB_DEBUG": ,
"DB_POOL": ,
"DB2CODEPAGE": ,
"MAIL_HOST": "",
"MAIL_USER": "",
"MAIL_PASSWORD": "",
"MAIL_FROM": "",
"MAIL_ERRORS_TO": [""],
"AT_SECRET":"",
"AT_EXPIRES_IN":"",
"RT_SECRET":"",
"RT_EXPIRES_IN":""
}
}]}

#

I empty the values for safety reasons

fiery karma
#

pm2 is not a production environment/server/server hosting provider, it's a way to run your processes, right? Who is your server host provider? AWS, GCP, DigitalOcean, self-hosted, cycle, render, something else? (there's way too many for me to remember)

loud shard
#

self-hosted

fiery karma
#

So do you have a .env file on the production server, or do you have these values hardcoded in that ecosystem.config.js file?

loud shard
#

values hardcoded

#

the thing I dont understand is how the app can see the rest of the variables like the data base connection

#

that makes me think that the issue comes from the code and not from the deployment

fiery karma
#

It might? From what you've shaerd in the StackOverflow though, things generally look fine

loud shard
#

you were right launching this command the app could see the env variable -> pm2 reload <process_name_or_id> --update-env

rain musk
#

@loud shard Maybe in your production enviroment headers not sent from client?