我在nestJS应用程序(使用authGuard)中使用了password-jwt auth策略,如何访问控制器中的令牌有效负载?

The*_*Guy 3 node.js jwt typescript nestjs passport-jwt

我正在尝试通过进行保护的路由中访问jwt有效负载AuthGuard

我正在使用passport-jwt,令牌有效载荷是用户的电子邮件。

我可以通过运行下面的代码来实现:

import {
    Controller,
    Headers,
    Post,
    UseGuards,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { AuthGuard } from '@nestjs/passport';

@Post()
@UseGuards(AuthGuard())
async create(@Headers() headers: any) {
    Logger.log(this.jwtService.decode(headers.authorization.split(' ')[1]));
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否有更好的方法?

Kim*_*ern 6

JwtStrategyvalidate方法。在这里您可以访问JwtPayload。该方法的返回值将附加到请求中(默认情况下,在属性中user)。因此,您可以从有效负载中返回所需的任何内容:

async validate(payload: JwtPayload) {
  const user = await this.authService.validateUser(payload);
  if (!user) {
    throw new UnauthorizedException();
  }
  return {user, email: payload.email};
}
Run Code Online (Sandbox Code Playgroud)

然后通过注入请求在控制器中访问它:

@Post()
@UseGuards(AuthGuard())
async create(@Req() request) {
    Logger.log(req.user.email);
}
Run Code Online (Sandbox Code Playgroud)

您可以通过创建自定义装饰器使此操作更加方便:

import { createParamDecorator } from '@nestjs/common';

export const User = createParamDecorator((data, req) => {
  return req.user;
});
Run Code Online (Sandbox Code Playgroud)

然后注入@User而不是@Req