NestJS / NodeJS / Passport / JWT - 股票当前用户

Posted

技术标签:

【中文标题】NestJS / NodeJS / Passport / JWT - 股票当前用户【英文标题】:NestJS / NodeJS / Passport / JWT - Stock current user 【发布时间】:2020-08-26 15:47:44 【问题描述】:

我有一个 NestJS 后端,由 JWT 保护。 我想知道存储实际用户的最佳方式或将其传递给我的服务的最佳方式是什么?

我有一个 JwtAuthGuard

@Injectable()
export class JwtAuthGuard extends AuthGuard( 'jwt' ) 
  canActivate(context: ExecutionContext) 
    return super.canActivate( context );
  

  handleRequest(err, user, info) 
    if ( err || !user ) 
      throw err || new UnauthorizedException();
    
    return user;
  

我的实际用户 ID 在 handleRequest 的 user var 中,但我不知道在哪里“储存”它以便能够在某些模块中访问它。 有谁可以帮助我吗?

谢谢

【问题讨论】:

【参考方案1】:

JWT 本身是您存储用户 ID(或用户的任何识别详细信息)的位置。

如果您使用用户 ID ( id: 123, ... ) 创建 JWT 有效负载,则护照会将 user 成员设置为 request 对象。

重要提示:不要在 JWT 中存储敏感数据。

  @AuthGuard( 'jwt' )
  @Get('profile')
  getUserId(@Request() req: any) 
    return req.user.id;
  

您可以根据需要将req.user.id 传递给服务。

见:https://docs.nestjs.com/techniques/authentication#implement-protected-route-and-jwt-strategy-guards


最后一件事: 如果你喜欢请求对象的类型,你可以这样做

import  Request as HttpRequest  from 'express';


interface UserJwtPayload 
  id: string,

type AuthRequest = HttpRequest &  user: UserJwtPayload 

【讨论】:

以上是关于NestJS / NodeJS / Passport / JWT - 股票当前用户的主要内容,如果未能解决你的问题,请参考以下文章