'How to get the JWT's secretOrKey from remote in NestJS?
Here is my code to verify incoming request using JWT in NestJS:
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: 'test',
});
}
async validate(payload: any) {
return {
userId: payload.sub,
username: payload.username,
};
}
}
It works well when I set the secretOrKey to 'test' (define the secretOrKey locally). For security reason, I want to read the secretOrKey from the key/value in Consul (or Redis):
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { listSecret } from './constants';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly Secret: listSecret) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: Secret.listSec(),
});
}
async validate(payload: any) {
return {
userId: payload.sub,
username: payload.username,
};
}
}
Here is the listSecret:
import { Consul } from '../Consul';
import { Inject, Injectable } from '@nestjs/common';
@Injectable()
export class listSecret {
constructor(
private consul: Consul,
) {}
async listSec() {
const JWT_KEY = await this.consul.ConsulUse(
'https://192.168.1.1:8501/v1/kv/jwt',
);
return JWT_KEY;
}
}
When I run the app to send a request with the JWT, I get the :
{
"statusCode": 401,
"message": "Unauthorized"
}
It seems that the secretOrKey could not get the right value (I guess it could have a 'Promise { < pending > }' in return). So, I think it would use 'async/await' in the constructor (jwt.strategy.ts), but I can not find a way to do that (the Consul is working well).
Thanks
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
