JWT Guard 返回“将循环结构转换为 JSON”

问题描述 投票:0回答:1

我有这个嵌套代码来验证用户登录后的不记名令牌,但它给了我错误:

ERROR [ExceptionsHandler] Converting circular structure to JSON
--> starting at object with constructor 'Socket'
|     property 'parser' -> object with constructor 'HTTPParser'
--- property 'socket' closes the circle

这是我的登录代码和我尝试授权用户的尝试: 用户.模块:

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    TypeOrmModule.forFeature([User, Level]),
    JwtModule.register({
      secret: 'abc123',
      signOptions: { expiresIn: '60d' },
    }),
  ],
  controllers: [UserController],
  providers: [UserService, JwtStrategy],
})
export class UserModule {}

用户.控制器:

import { jwtAuthGuard } from 'src/guards/jwt.guard';
 @Get("")
    @UseGuards(jwtAuthGuard)
    getUser(@Req() req: Request) {
        return this.UserService.getUser(req)
    }

jwt.guard:

import { ExecutionContext, Injectable } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
import { Observable } from "rxjs";

@Injectable()
export class jwtAuthGuard extends AuthGuard('jwt'){
    canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {        
        return super.canActivate(context)
    }

}

jwt.策略:

export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private userService: UserService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: 'abc123', // Access the environment variable
    });
  }

  validate(payload: any) {
    return payload;
  }
}

这是我的整个代码,我省略了一些导入以及控制器和其他模块中的一些代码,以免这篇文章太长

authentication jwt nestjs
1个回答
0
投票

解决方案在 user.conroller 中,我将整个

req
传递到
getUser(req)
方法中,这就是代码应该编写的方式:

 @Get("")
    @UseGuards(jwtAuthGuard)
    getUser(@Req() req: Request) {
        return this.UserService.getUser(req.body)
    }

所以从这个:

getUser(req)
getUser(req.body)

© www.soinside.com 2019 - 2024. All rights reserved.