🚀使用 HMAC 实现安全的 API 到 API 通信:使用 NestJS、AWS 和 Postman 实现🔥

介绍

在当今的互联系统中,安全性对于 API 通信至关重要。HMAC(基于哈希的消息认证码)是一种确保 API 调用的完整性和真实性的强大方法。

在本文中,我们将介绍:

  • HMAC 如何进行 API 到 API 调用。
  • 使用 NestJS 和 AWS(带有 UseGuards)逐步设置 HMAC。
  • 使用自定义脚本对受 HMAC 保护的端点进行 Postman 测试。
  • **1. HMAC 如何用于 API 到 API 调用**

    **什么是 HMAC?**

    HMAC 将密钥和消息结合起来以生成唯一的哈希值。这可确保:

  • 完整性:消息未被篡改。
  • 真实性:请求来自可信的发送者。
  • **视觉图表:**

    HMAC 的工作原理

    hmac

    **HMAC 流程**

  • 客户端:使用密钥和请求负载生成 HMAC 哈希。
  • 服务器:使用相同的密钥计算其自身的哈希值。
  • 验证:如果两个哈希值匹配,则请求有效。
  • **2. 使用 NestJS 和 AWS 设置 HMAC**

    **步骤 1:安装依赖项**

    安装必要的库:

    npm install crypto aws-sdk @nestjs/config

    **步骤 2:将密钥存储在 AWS Secrets Manager 中**

  • 转到 AWS 控制台 → Secrets Manager → 创建 Secret。
  • 安全地添加您的密钥。
  • 在您的 NestJS 应用程序中检索此密钥。
  • 可视化分步说明:

    hmac1

    **步骤 3:创建 HMAC 服务**

    hmac.服务.ts

    import { Injectable } from '@nestjs/common';
    import * as crypto from 'crypto';
    import { SecretsManager } from 'aws-sdk';
    
    @Injectable()
    export class HmacService {
      private secretKey: string;
    
      constructor() {
        this.loadSecret();
      }
    
      async loadSecret() {
        const secretsManager = new SecretsManager({ region: 'us-east-1' });
        const secret = await secretsManager
          .getSecretValue({ SecretId: 'your-secret-key' })
          .promise();
        this.secretKey = secret.SecretString || '';
      }
    
      generateHmac(payload: string): string {
        return crypto
          .createHmac('sha256', this.secretKey)
          .update(payload)
          .digest('hex');
      }
    
      validateHmac(payload: string, clientHash: string): boolean {
        const serverHash = this.generateHmac(payload);
        return serverHash === clientHash;
      }
    }

    **步骤 4:使用 Guards 进行 HMAC 验证**

    不要使用中间件,而要创建一个保护程序来验证 HMAC 哈希值。

    hmac.guard.ts

    import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
    import { HmacService } from './hmac.service';
    
    @Injectable()
    export class HmacGuard implements CanActivate {
      constructor(private readonly hmacService: HmacService) {}
    
      canActivate(context: ExecutionContext): boolean {
        const request = context.switchToHttp().getRequest();
        const payload = JSON.stringify(request.body);
        const clientHmac = request.headers['x-hmac-signature'] as string;
    
        if (!clientHmac || !this.hmacService.validateHmac(payload, clientHmac)) {
          throw new UnauthorizedException('Invalid HMAC signature');
        }
    
        return true; // Allow request if HMAC is valid
      }
    }

    **步骤 5:将 UseGuards 应用于路由**

    应用程序.控制器.ts

    import { Controller, Post, Body, UseGuards } from '@nestjs/common';
    import { HmacGuard } from './hmac.guard';
    
    @Controller('secure-endpoint')
    export class AppController {
      @Post()
      @UseGuards(HmacGuard)
      handleSecureEndpoint(@Body() data: any) {
        return { message: 'Request successfully validated!', data };
      }
    }

    视觉表现:-

    Image2

    **3. 使用 Postman 测试 HMAC 安全端点**

    **步骤 1:添加预请求脚本**

    在 Postman 中动态生成 HMAC 哈希:

    预请求脚本:

    const crypto = require('crypto');
    
    // Payload
    const payload = JSON.stringify({
      data: 'Sample request payload',
    });
    
    // Secret Key (replace with your key)
    const secretKey = 'your-shared-secret-key';
    
    // Generate HMAC Hash
    const hash = crypto
      .createHmac('sha256', secretKey)
      .update(payload)
      .digest('hex');
    
    // Add HMAC hash to headers
    pm.request.headers.add({
      key: 'x-hmac-signature',
      value: hash,
    });
    
    console.log('Generated HMAC:', hash);

    **步骤 2:配置 Postman 请求**

  • 方法:POST
  • 标题:由脚本自动设置。
  • 正文:以 JSON 格式添加有效负载。
  • 示例有效载荷:

    {
      "data": "Sample request payload"
    }

    **步骤 3:测试并验证**

  • 点击“发送”。
  • 如果 HMAC 有效,您将收到 200 OK 响应。
  • **结论**

    通过使用 NestJS 实现 HMAC 并使用 Postman 进行测试,您可以确保:

  • API 到 API 通信的完整性和真实性。
  • 一种使用 UseGuards 进行路线保护的干净、模块化方法。
  • 使用 AWS Secrets Manager 进行安全密钥管理。
  • **关键要点**

  • 使用 HMAC Guards 进行可扩展和模块化验证。
  • 使用 AWS Secrets Manager 安全地管理共享机密。
  • 使用 Postman 脚本轻松测试 HMAC 验证。
  • 请告诉我你如何在系统中实现 HMAC!🚀

    与我联系以获取更多 API 安全见解。

    NestJS #AWS #HMAC #APISecurity #Postman #BackendDevelopment #SpringBoot #JavaDevelopment #Microservices #SpringCloud #BackendDevelopment #RESTAPI #DevTools #SoftwareEngineering #SpringBootTesting #JWTAuthentication #DistributedTracing #EventDrivenArchitecture #EurekaServer #SpringSecurity #APIIntegration #Technology #Programming #Coding #SoftwareEngineering #TechInnovation #TechCommunity #JavaScript #Python #TypeScript #Golang #Java #RubyOnRails #CSharp #PHP #Swift #Kotlin #Rust #SQL #HTML #CSS #NodeJS #ReactJS #AngularJS #VueJS #Django #Flask #SpringBoot #CloudComputing #Blockchain #AI #MachineLearning #APIDevelopment #Cyber​​Security #ScalableArchitecture #BackendDevelopment #DevOps#AWS#Terraform #DynamoDB #NestJS#CleanCode#技术趋势#技能提升#技术职业#创新#最佳实践