API keys giống như chìa khóa cửa trước của dịch vụ bạn—chúng cho người dùng vào mà vẫn giữ mọi thứ an toàn. Trong blog này, tôi sẽ hướng dẫn bạn xây dựng một trình tạo API key đơn giản, an toàn sử dụng Upstash Redis để lưu trữ dữ liệu không máy chủ, nhanh chóng và Cloudflare Workers để xử lý yêu cầu ở edge. Dù bạn đang thiết lập dịch vụ mới hay thêm keys vào ứng dụng hiện có, bạn sẽ học cách tạo, lưu trữ và xác thực API keys để giữ mọi thứ chạy trơn tru và hiệu quả.
API Key Là Gì?
API key là một mã duy nhất xác định và xác thực người dùng hoặc ứng dụng cố gắng truy cập API của bạn. Hãy nghĩ nó như một thẻ thông hành cá nhân: khi ai đó muốn sử dụng dịch vụ của bạn, họ cần xuất trình "chìa khóa" này để chứng minh họ được phép vào. API keys giúp bạn kiểm soát ai có thể truy cập tài nguyên của bạn, và chúng thường được dùng để theo dõi sử dụng, thực thi giới hạn, hoặc ngăn chặn truy cập trái phép. Chúng là một cách trực quan để quản lý truy cập API và giữ an toàn dữ liệu của bạn.
Chúng Ta Sẽ Xây Dựng Gì
Trong hướng dẫn này, chúng ta sẽ tạo một trình tạo api key cung cấp hai chức năng cốt lõi:
- Tạo API keys mới với cài đặt tùy chỉnh
- Xác thực API keys trong khi truy xuất metadata của chúng
Các tính năng chính sẽ bao gồm:
- Tiền tố key tùy chỉnh
- Ngày hết hạn
- Giới hạn tỷ lệ (rate limiting)
- Lưu trữ metadata
- Nhận diện chủ sở hữu
Hãy Trình Diễn Hệ Thống API Key Của Chúng Ta
Sơ đồ này minh họa tương tác giữa client, Cloudflare Worker của chúng ta, và Upstash Redis cho cả việc tạo và xác thực API keys. Với cái nhìn tổng quan này, hãy bắt đầu xây dựng hệ thống của chúng ta.

Điều Kiện Tiên Quyết
Để làm theo, bạn sẽ cần:
- Một tài khoản Cloudflare Workers
- Một tài khoản Upstash
- Node.js được cài đặt trên máy cục bộ
Cấu Trúc Dự Án
Dự án của chúng ta sẽ có cấu trúc sau:
folder-name/ ├── src/ │ ├── config/ │ │ ├── generateApiKey.ts │ │ └── schema-validation.ts │ ├── lib/ │ │ └── ratelimit.ts │ ├── routes/ │ │ ├── create.ts │ │ └── verify.ts │ ├── types/ │ │ └── api.ts │ └── index.ts ├── package.json └── wrangler.toml
Bước 1: Thiết Lập Dự Án
Hãy bắt đầu bằng cách thiết lập dự án và cài đặt các phụ thuộc cần thiết.
Tạo Thư Mục Dự Án Mới
Mở terminal và chạy các lệnh sau:
mkdir keyflow cd keyflow npm init -y
Cài Đặt Phụ Thuộc
Chúng ta sẽ cần một vài gói cho dự án:
npm install hono @upstash/redis @upstash/ratelimit @hono/zod-validator zod wrangler
@upstash/redis: Client Upstash Redis cho môi trường không máy chủ @upstash/ratelimit: Thư viện giới hạn tỷ lệ cho Upstash Redis @hono/zod-validator: Middleware xác thực request cho Hono zod: Thư viện xác thực lược đồ ưu tiên TypeScript wrangler: CLI của Cloudflare cho phát triển và triển khai Workers
Thiết Lập Upstash Redis
- Đăng nhập tài khoản Upstash và tạo cơ sở dữ liệu Redis mới

- Sau khi tạo, điều hướng đến phần "REST API"

- Sao chép
UPSTASH_REDIS_REST_URLvàUPSTASH_REDIS_REST_TOKENtrong phần.env
Cấu Hình Cloudflare Workers
Tạo tệp wrangler.toml trong thư mục gốc dự án với nội dung sau:
name = "keyflow" main = "src/index.ts" compatibility_date = "2023-05-18" [vars] UPSTASH_REDIS_REST_URL = "your-redis-url" UPSTASH_REDIS_REST_TOKEN = "your-redis-token"
Thay thế "your-redis-url" và "your-redis-token" bằng các giá trị bạn đã sao chép từ Upstash.
Bước 2: Định Nghĩa Các Kiểu API
Hãy bắt đầu bằng cách định nghĩa các interface TypeScript cho request và response API của chúng ta. Các kiểu này sẽ giúp chúng ta duy trì an toàn kiểu xuyên suốt ứng dụng. Tạo tệp mới src/types/api.ts:
export type CreateKeyRequest = { apiId: string; prefix?: string; byteLength?: number; ownerId?: string; name: string; meta?: Record<string, unknown>; expires?: number; ratelimit?: { type: "fast" | "consistent"; limit: number; refillRate: number; refillInterval: number; }; }; export type CreateKeyResponse = { key: string; keyId: string; }; export type VerifyKeyRequest = { key: string; }; export type VerifyKeyResponse = { valid: boolean; ownerId?: string; meta?: Record<string, unknown>; expires?: number; ratelimit?: { limit: number; remaining: number; reset: number; }; }; export type Env = { UPSTASH_REDIS_REST_URL: string; UPSTASH_REDIS_REST_TOKEN: string; };
Bước 3: Triển Khai Tạo API Key
Bây giờ, hãy tạo một hàm tiện ích để tạo API keys của chúng ta. Tạo tệp mới src/config/generateApiKey.ts:
export function generateApiKey( prefix: string | undefined, byteLength: number, ): string { const randomBytes = crypto.getRandomValues(new Uint8Array(byteLength)); const key = btoa(String.fromCharCode(...new Uint8Array(randomBytes))) .replace(/\+/g, "-") .replace(/\//g, "_") .replace(/=/g, ""); return prefix ? `${prefix}_${key}` : key; }
Hàm này tạo một API key ngẫu nhiên sử dụng các byte ngẫu nhiên an toàn mật mã, mã hóa nó trong base64, và làm cho nó an toàn cho URL.
Bước 4: Triển Khai Giới Hạn Tỷ Lệ
Tạo tệp src/lib/ratelimit.ts:
import { Ratelimit } from "@upstash/ratelimit"; import { Redis } from "@upstash/redis/cloudflare"; import type { Context, Next } from "hono"; import { env } from "hono/adapter"; import type { Env } from "../types/api"; // Middleware cho rate limiting export async function rateLimitMiddleware(c: Context, next: Next) { const { UPSTASH_REDIS_REST_TOKEN, UPSTASH_REDIS_REST_URL } = env<Env>(c); const redis = new Redis({ url: UPSTASH_REDIS_REST_URL, token: UPSTASH_REDIS_REST_TOKEN, }); const ratelimit = new Ratelimit({ redis: redis, limiter: Ratelimit.slidingWindow(5, "30 s"), }); const ip = c.req.header("CF-Connecting-IP") || "127.0.0.1"; const { success, limit, remaining, reset } = await ratelimit.limit(ip); if (!success) { return c.json({ error: "Rate limit exceeded" }, 429); } c.header("X-RateLimit-Limit", limit.toString()); c.header("X-RateLimit-Remaining", remaining.toString()); c.header("X-RateLimit-Reset", reset.toString()); await next(); }
Bước 5: Tạo Các API Routes
Hãy thiết lập tệp ứng dụng chính và tạo API routes của chúng ta. Tệp này thiết lập ứng dụng Hono của chúng ta với hai route chính: /keys/create để tạo API keys mới và /keys/verify để xác thực keys hiện có với ba tệp riêng biệt.
1. Triển Khai Route Tạo API Key
Tạo tệp src/routes/create.ts:
import { zValidator } from "@hono/zod-validator" import { Redis } from "@upstash/redis/cloudflare" import { Hono } from "hono" import { generateApiKey } from "../config/generateApiKey" import { createApiKeySchema } from "../config/schema-validation" import type { CreateKeyRequest, CreateKeyResponse, Env } from "../types/api" const create = new Hono<{ Bindings: Env }>() create.post( "/create", zValidator("json", createApiKeySchema, (result, c) => { if (!result.success) { return c.text("Invalid!", 400) } }), async (c) => { // Initialize Redis client const { UPSTASH_REDIS_REST_TOKEN, UPSTASH_REDIS_REST_URL } = c.env const redis = new Redis({ url: UPSTASH_REDIS_REST_URL, token: UPSTASH_REDIS_REST_TOKEN, }) const body = await c.req.json<CreateKeyRequest>() // Generate unique identifier and API key const keyId = crypto.randomUUID() const key = generateApiKey(body.prefix, body.byteLength || 16) const keyData = { ...body, key, keyId, createdAt: Date.now(), } const encodedKey = encodeURIComponent(key) try { // Store key data and lookup reference in Redis await redis.set(`key:${keyId}`, JSON.stringify(keyData)) await redis.set(`lookup:${encodedKey}`, keyId) return c.json<CreateKeyResponse>({ key, keyId }) } catch (error) { console.error("Error in /keys/create:", error) return c.json({ error: "Internal Server Error" }, 500) } } ) export default create
2. Triển Khai Route Xác Thực API Key
Tạo tệp src/routes/verify.ts:
import { zValidator } from "@hono/zod-validator"; import { Redis } from "@upstash/redis/cloudflare"; import { Hono } from "hono"; import { verifyApiKeySchema } from "../config/schema-validation"; import type { CreateKeyRequest, Env, VerifyKeyRequest, VerifyKeyResponse, } from "../types/api"; // Initialize Hono app with environment bindings const verify = new Hono<{ Bindings: Env }>(); // Define POST route for verifying an API key verify.post( "/verify", // Validate request body against schema zValidator("json", verifyApiKeySchema, (result, c) => { if (!result.success) { return c.text("Invalid!", 400); // Return 400 if validation fails } }), async (c) => { // Set up Redis with environment variables const { UPSTASH_REDIS_REST_TOKEN, UPSTASH_REDIS_REST_URL } = c.env; const redis = new Redis({ url: UPSTASH_REDIS_REST_URL, token: UPSTASH_REDIS_REST_TOKEN, }); const body = await c.req.json<VerifyKeyRequest>(); if (!body.key) { return c.json({ error: "key is required" }, 400); // Require key in the request body } const encodedKey = encodeURIComponent(body.key); const keyId = await redis.get<string>(`lookup:${encodedKey}`); // Retrieve key ID using encoded key if (!keyId) { return c.json<VerifyKeyResponse>({ valid: false }); // Key not found } const keyDataString = await redis.get<string>(`key:${keyId}`); // Retrieve key data by key ID if (!keyDataString || typeof keyDataString !== "string") { return c.json<VerifyKeyResponse>({ valid: false }); // Key data missing or invalid } let keyData: CreateKeyRequest & { key: string; keyId: string; createdAt: number; }; try { keyData = JSON.parse(keyDataString); // Parse key data } catch (parseError) { // Handle parse error by deleting invalid data console.error("Key data parse error:", parseError); await Promise.all([ redis.del(`key:${keyId}`), redis.del(`lookup:${encodedKey}`), ]); return c.json( { error: "Invalid key data in storage", details: parseError instanceof Error ? parseError.message : "Unknown parse error", valid: false, }, 500, ); } // Check if key has expired if (keyData.expires && keyData.expires < Date.now()) { await Promise.all([ redis.del(`key:${keyId}`), redis.del(`lookup:${encodedKey}`), ]); return c.json<VerifyKeyResponse>({ valid: false }); } // Formulate response with validation status and metadata const response: VerifyKeyResponse = { valid: true, ownerId: keyData.ownerId, meta: keyData.meta, expires: keyData.expires, }; if (keyData.ratelimit) { response.ratelimit = { limit: keyData.ratelimit.limit, remaining: keyData.ratelimit.limit, reset: Date.now() + keyData.ratelimit.refillInterval, }; } return c.json(response); // Return verification response }, ); export default verify;
3. Triển Khai Tệp Chính index.ts
triển khai tệp chính src/index.ts để nhập create.ts, verify.ts, và rateLimitMiddleWare
import { Hono } from "hono"; import { rateLimitMiddleware } from "./lib/ratelimit"; import create from "./routes/create"; import verify from "./routes/verify"; import type { Env } from "./types/api"; const app = new Hono<{ Bindings: Env; }>().basePath("/keys"); app.use("*", rateLimitMiddleware); // add the create file route and verify file route app.route("/", create); app.route("/", verify); export default app;
Bước 6: Triển Khai
Triển khai ứng dụng Keyflow của bạn lên Cloudflare Workers:
-
Cài đặt Wrangler:
npm install -g wrangler -
Xác thực với Cloudflare:
wrangler login -
Triển khai worker của bạn:
wrangler deploy
Bước 7: Triển Khai
Bây giờ chúng ta đã sẵn sàng ứng dụng, hãy triển khai nó lên Cloudflare Workers:
-
Đảm bảo bạn đã cài đặt Wrangler CLI:
npm install -g wrangler -
Xác thực với tài khoản Cloudflare của bạn:
wrangler login -
Triển khai worker của bạn:
wrangler deploy
Bước 8: Kiểm Thử API Của Bạn
Hãy kiểm tra API mới triển khai của chúng ta:
Tạo API Key Mới
curl -X POST https://keyflow.<your-subdomain>.workers.dev/keys/create \ -H "Content-Type: application/json" \ -d '{ "apiId": "my-api", "prefix": "prod", "name": "Production API Key", "expires": 1735689600000, "meta": { "environment": "production", "team": "backend" } }'
Xác Thực API Key
curl -X POST https://keyflow.<your-subdomain>.workers.dev/keys/verify \ -H "Content-Type: application/json" \ -d '{ "key": "prod_AbC123XyZ..." }'
Thay thế <your-subdomain> bằng subdomain Cloudflare Workers của bạn và prod_AbC123XyZ... bằng key thực tế được tạo từ endpoint create.
Kết Luận
Tạo một trình tạo API key là bước quan trọng trong việc bảo mật API của ứng dụng và quản lý ai có thể truy cập dịch vụ của bạn. Bằng cách xây dựng một hệ thống có thể tạo, xác thực và quản lý API keys, bạn thêm một lớp kiểm soát truy cập mạnh mẽ giúp giữ an toàn và tổ chức dữ liệu của bạn.
Dưới đây là tóm tắt nhanh những gì cần cho một trình tạo API key vững chắc:
- Tạo Key An Toàn: Các key duy nhất, an toàn bao gồm các tùy chọn như tiền tố tùy chỉnh hoặc độ dài đặt trước làm cho mỗi key riêng biệt và khó đoán hơn.
- Xác Thực Và Hết Hạn: Thêm các kiểm tra và ngày hết hạn đảm bảo mỗi key chỉ hợp lệ trong một thời gian đặt trước, làm cho việc kiểm soát và giới hạn truy cập trở nên dễ dàng khi cần.
- Metadata Và Giới Hạn Tỷ Lệ: Lưu trữ thông tin thêm với mỗi key và đặt giới hạn tỷ lệ cho phép bạn theo dõi sử dụng key, theo dõi hoạt động, và tránh lạm dụng API của bạn.
Sử dụng các công cụ như Upstash Redis và Cloudflare Workers làm cho việc xây dựng một hệ thống quản lý key không máy chủ và phân bố toàn cầu trở nên dễ dàng, mở rộng tốt và hoạt động hiệu quả.
Với nền tảng này, bạn đã sẵn sàng để giữ truy cập API của bạn an toàn và có thể quản lý, mang lại sự an tâm rằng tài nguyên của bạn được bảo vệ và dễ dàng theo dõi.