学习在 NestJS 中构建 API

2022/11/17 23:24:53

本文主要是介绍学习在 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();
  }
}

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

  • jwtFromRequest:定义在何处查找 jwt 令牌 (它可能是授权标头以外的另一个地方...我们将坚持使用经典的承载模式。为此,值应该是。这似乎映射到护照文档的这一部分和这部分,内容涉及从请求中提取 jwt 令牌。

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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。



这篇关于学习在 NestJS 中构建 API的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程