0

I'm trying use .env to read the JWT secret and validate my tokens.

My class at this moment is loading the .env and reading the value, after that I can create a token:

export default class AuthMiddleware {
  constructor() {
  }

  private async getJWTSecret(): Promise<string> {
    await dotenvSafe.config();
    let JWTSecret = await process.env.JWT_SECRET || "g&n&r1c5&cre7";
    return JWTSecret;
  }

  public async createJWTToken(user: UserModel): Promise<any> {
    const JWTSecret = await this.getJWTSecret();
    let payloadJWTToken: {};
    payloadJWTToken = { userId: user.id, role: "GENERIC", iss: "My Company", iat: 1516239022, aud: "https://www.mycompany.com.br/"};
    let JWTToken = jwt.sign(payloadJWTToken, JWTSecret);
    return JWTToken;
  }
}

Now I adding the method to validate the token I'm trying read the .env in the same way:

public async checkJWTToken(req: Request, res: Response, next: NextFunction): Promise<any> {
    const JWKtokenInRequestHeader = <string>req.headers["authorization"];

    try {
      this.getJWTSecret().then(secret => console.log(`Secret: ${secret}`))
      .catch(error => console.log(`An error has occurred: ${error}`));

    } catch (erro) {
      console.log(`Error message: ${erro}`);
    }

    next();
}

But I received this error message:

Error message: TypeError: Cannot read property 'getJWTSecret' of undefined

I can't undertend why I read this .env in the same way in another method and it worked fine, and now don't work.

Some tip?

Jean J. Michel
  • 561
  • 1
  • 7
  • 14
  • that error message has nothing to do with reading the `.env` from process. It is clearly saying the `this` keyword is undefined when calling `this.getJWTSecret()`. Your scoping is incorrect in that method. I'm guessing because the `checkJWTToken()` method is called as part of a callback. – Randy Casburn Jun 23 '19 at 14:50
  • Your `this` does not refer to the same context that contains the getJWTSecret method. Also, you are using a `.catch` within a try and catch which will also cause issues, though probably unrelated. – Yeysides Jun 23 '19 at 14:52
  • Thanks guys. I turned the method static and works fine now. – Jean J. Michel Jun 23 '19 at 23:03

0 Answers0