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?