'extract payload from JWT token

JWT.Strategy

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, "jwt") {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([
        (request: Request) => {
          let data = request?.cookies["auth-cookie"];
          if (!data) {
            return null;
          }

          return data.token;
        },
      ]),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
    });
  }

  async validate(payload: any) {
    if (payload === null) {
      throw new UnauthorizedException();
    }
    return payload;
  }
}

User.Controller

 @UseGuards(JwtAuthGuard)
  @Get("me")
  getUserInfo(@Req() req) {
    return req.user;
  }

Need to retrieve username from JWT token payload, but i just receive the whole token.. The Problem is that i don't know how to decode the token correctly. Could you please help?



Solution 1:[1]

May be this could help you:

async validate(payload: JwtPayload): Promise<any> {
    const { username } = payload;
    const user = await this.userService.getUserInfo({ username });

    if (!user) {
      throw new ForbiddenException(CommonError.FORBIDDEN);
    }
    
    return user;
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ?oàn ??c B?o