🚀使用 HMAC 实现安全的 API 到 API 通信:使用 NestJS、AWS 和 Postman 实现🔥
介绍
在当今的互联系统中,安全性对于 API 通信至关重要。HMAC(基于哈希的消息认证码)是一种确保 API 调用的完整性和真实性的强大方法。
在本文中,我们将介绍:
**1. HMAC 如何用于 API 到 API 调用**
**什么是 HMAC?**
HMAC 将密钥和消息结合起来以生成唯一的哈希值。这可确保:
**视觉图表:**
HMAC 的工作原理

**HMAC 流程**
**2. 使用 NestJS 和 AWS 设置 HMAC**
**步骤 1:安装依赖项**
安装必要的库:
npm install crypto aws-sdk @nestjs/config
**步骤 2:将密钥存储在 AWS Secrets Manager 中**
可视化分步说明:

**步骤 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 };
}
}视觉表现:-

**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 请求**
示例有效载荷:
{
"data": "Sample request payload"
}**步骤 3:测试并验证**
**结论**
通过使用 NestJS 实现 HMAC 并使用 Postman 进行测试,您可以确保:
**关键要点**
请告诉我你如何在系统中实现 HMAC!🚀
与我联系以获取更多 API 安全见解。