其他分享
首页 > 其他分享> > 学习在 NestJS 中构建 API

学习在 NestJS 中构建 API

作者:互联网

生成令牌

NestJS有敬畏的可以安装(文档)。❤️JwtModule

npm i @nestjs/jwt

它具有可以对用户令牌进行签名的服务。我们的身份验证服务应使用它来执行登录操作。

import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';

@Injectable({})
export class AuthenticationService {
  constructor(private readonly jwtService: JwtService) {
    this.jwtService = jwtService;
  }
  async signIn(user: any): Promise<any> {
    // Here we should map the user entity to a stripped-down object
    const userInfo = { username: 'username', sub: 'sub' };
    return this.jwtService.sign(userInfo);
  }
}

请记住,如果我们使用服务,则需要导入它来自的模块。此特定导入包含一些需要提供的配置参数。这些涉及令牌的到期时间、哈希算法、密钥等......这些参数来自底层库jsonwebtoken。
因此,我们将导入一个幻想的秘密:
AuthenticationModuleJtwModule

import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { AuthenticationService } from './authentication.service';
import { JwtModule } from '@nestjs/jwt';

@Module({
  imports: [PassportModule, JwtModule.register({ secret: 'secret-key' })],
  providers: [AuthenticationService],
})
export class AuthenticationModule {}

获取令牌以供将来请求

因此,现在我们应该创建一个将返回令牌的登录终结点。

// All other imports
// ...
import { AuthenticationService } from 'src/authentication/authentication.service';

@Controller('example')
export default class ExampleController {
  constructor(
    private readonly exampleService: ExampleService,
    private readonly authenticationService: AuthenticationService,
  ) {}

  @Get('sign-in')
  async signIn() {
    return await this.authenticationService.signIn({});
  }

  // All the other endpoints
  //...
}

这看起来不错。下一步是通过检查请求的授权标头中是否存在有效的持有者令牌来保护其余终结点。为此,我们需要在服务器管道中实现身份验证步骤。

实施护照

查看官方文档,有一个身份验证部分。它介绍了库。passport

Passport 为我们提供了负责解析请求并验证 jwt 令牌是否有效的中间件。

我们需要安装核心节点库(),支持jwt策略的底层代码(),NestJS包装器(),以及一些易于开发的类型()。passportpassport-jwt@nestjs/passport@types/passport-jwt

npm install passport passport-jwt @nestjs/passport
npm install -D @types/passport-jwt

那么 Passport 如何知道 jwt 令牌是否有效?

配置护照 JWT 策略

以同样的方式,我们配置了NestJS的JwtModule来构建我们的jwt令牌,Passport需要配置相同的参数才能正确解析令牌。

为了配合约定,此配置位于身份验证文件夹内的文件中。它定义了一个类,该类负责使用所需的配置扩展基本护照策略类。这包括实现一个将使用用户验证回调的函数(我们需要对此回调进行编码)。此类将作为提供程序提供,供应用程序的其余部分使用。这意味着策略类应该用。该文件应如下所示:jwt.strategy.tsvalidateAuthenticationModule@Injectable()

// import the specific strategy from Passport
import { Strategy } from 'passport-jwt';
// import NestJS passport wrapper
import { PassportStrategy } from '@nestjs/passport';
// import the Injectable decorator to allow this class to be imported into the AuthenticationModule
import { Injectable } from '@nestjs/common';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super();
  }
}

为了使它正常工作,我们需要向基构造函数添加一些参数。我们将提供两个最基本的:

标签:NestJS,构建,生成令牌,文档,编码,令牌
来源: