0

智威汤逊策略

@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;
  }
}

用户控制器

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

需要从 JWT 令牌有效负载中检索用户名,但我只收到整个令牌。问题是我不知道如何正确解码令牌。能否请你帮忙?

4

1 回答 1

0

可能这可以帮助你:

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;
  }
于 2022-03-01T09:52:57.220 回答