undefined when accessing an object in NestJS

huangapple go评论56阅读模式
英文:

undefined when accessing an object in NestJS

问题

I am building a NestJS API with JWT Token and Refresh Token.

When I am trying to get a new access token using the refresh token, I am running into a strange issue.

I noticed that when I am generating a new access token using the refreshToken function, it contains an empty payload. When I investigated the issue, I found out that when I write console.log(user), I can see the values of the user object in the console. However, when I start accessing the properties of the user object to populate the payload, they are all undefined.

Here code for the refresh token strategy:

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

@Injectable()
export class RefreshJwtStrategy extends PassportStrategy(
  Strategy,
  'jwt-refresh',
) {
  constructor(private readonly configService: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromBodyField('refresh'),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>('jwt.refreshSecret'),
    });
  }

  async validate(payload: any) {
    return { user: payload.sub, userId: payload.userId };
  }
}

Here is the code in the controller:

@UseGuards(RefreshJwtGuard)
@Post('/refresh')
async refreshToken(@Request() req) {
    return await this.authService.refreshToken(req.user);
  }

Here is the code for the refreshToken:

async refreshToken(user: User) {
    console.log(user); // It is working fine and I can see the object and its values
    const payload = {
      userId: user.id, // undefined
      sub: {
        id: user.id, // undefined
        username: user.username, // undefined
        email: user.email, // undefined
      },
    };
    console.log(payload); // the payload is showing as {}
    return {
      accessToken: this.jwtService.sign(payload),
    };
  }

This is what I am getting from logging the user:

{
  user: {
    id: '8c5370bd-3b5c-404c-8362-fdb6efb84d75',
    username: 'owner1.1',
    email: 'owner1.1@gmail.com'
  },
  userId: '8c5370bd-3b5c-404c-8362-fdb6efb84d75'
}

This is what I am getting when I am logging the Payload after attempting to get the values from the user:

{
  userId: undefined,
  sub: { id: undefined, username: undefined, email: undefined }
}

Any idea how to solve this? What is the issue?

英文:

I am building a NestJS API with JWT Token and Refresh Token.

When I am trying to get a new access token using the refresh token, I am running into a strange issue.

I noticed that when I am generating a new access token using the refreshToken function, it contains an empty payload. When I investigated the issue, I found out that when I write consol.log(user), I can see the values of the user object in the concol. However, when I start accessing the properties of the user object to populate the payload, they are all undefined.

Here code for the refresh token strategy:

import { Injectable } from &#39;@nestjs/common&#39;;
import { ConfigService } from &#39;@nestjs/config&#39;;
import { PassportStrategy } from &#39;@nestjs/passport&#39;;
import { ExtractJwt, Strategy } from &#39;passport-jwt&#39;;

@Injectable()
export class RefreshJwtStrategy extends PassportStrategy(
  Strategy,
  &#39;jwt-refresh&#39;,
) {
  constructor(private readonly configService: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromBodyField(&#39;refresh&#39;),
      ignoreExpiration: false,
      secretOrKey: configService.get&lt;string&gt;(&#39;jwt.refreshSecret&#39;),
    });
  }

  async validate(payload: any) {
    return { user: payload.sub, userId: payload.userId };
  }
}

Here is the code in the controller:

@UseGuards(RefreshJwtGuard)
@Post(&#39;/refresh&#39;)
 async refreshToken(@Request() req) {
    return await this.authService.refreshToken(req.user);
  }

Here is the code for the refreshToken:

async refreshToken(user: User) {
    console.log(user); //It is working fine and I can see the object and it&#39;s values
    const payload = {
      userId: user.id, //undefined
      sub: {
        id: user.id, //undefined
        username: user.username, //undefined
        email: user.email, //undefined
      },
    };
    console.log(payload); //the payload is showing as {}
    return {
      accessToken: this.jwtService.sign(payload),
    };
  }

This is what I am getting from logging the user:

{
  user: {
    id: &#39;8c5370bd-3b5c-404c-8362-fdb6efb84d75&#39;,
    username: &#39;owner1.1&#39;,
    email: &#39;owner1.1@gmail.com&#39;
  },
  userId: &#39;8c5370bd-3b5c-404c-8362-fdb6efb84d75&#39;
}

This is what I am getting when I am logging the Payload after attempting to get the values from the user:

{
  userId: undefined,
  sub: { id: undefined, username: undefined, email: undefined }
}

Any idea how to solve this? what is the issue?

答案1

得分: 2

你的 user 对象是一个具有名为 user 的属性的对象,它是另一个包含用户信息的对象,因为你在 validate 函数中返回它:

return { user: payload.sub, userId: payload.userId }; // 这是你的 "user" 对象

因此,你需要从 user.user 而不是 user 中获取你想要的内容:

const payload = {
    userId: user.user.id,
    sub: {
      id: user.user.id,
      username: user.user.username,
      email: user.user.email,
    },
};

你也可以更新你的 validate 函数并保持代码不变:

async validate(payload: any) {
    return payload.sub
}
英文:

Your user object is an object with a property called user, it is another object that contain the user informations because you are returning this with the validate function:

return { user: payload.sub, userId: payload.userId }; // this is your &quot;user&quot; object

Therefore you have to get what you want from user.user instead of user

const payload = {
    userId: user.user.id,
    sub: {
      id: user.user.id,
      username: user.user.username,
      email: user.user.email,
    },
};

You can also update your validate function and keep your code as it is:

async validate(payload: any) {
    return payload.sub
}

huangapple
  • 本文由 发表于 2023年6月6日 03:14:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76409392.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定