英文:
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 '@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 it'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: '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?
答案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 "user" 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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论