ブログ · · 約 9 分で
署名検証のための生の本文の取得方法:Express・Next.js・Hono・FastAPI・Django・Rails・Laravel・Go
Webhook の
要点
- 署名は
届いた バイト列に 対して 計算されるので、 JSON の parser より 前に、 Webhook の 経路だけ生の 本文を 受け取ります。 - Express は
express.raw、 Next.js の App Router は request.text()、 FastAPI は await request.body()、 Django は request.body、 Rails は request.raw_post、 Laravel は $request->getContent()、 Go は io.ReadAll(r.Body) です。 - よく
ある 落とし穴は、 全体に JSON の parser を 掛けている、 文字列に 変換する ときに 文字コードや 改行が 変わる、 CSRF の 保護で 拒否される、 の 3 つです。
Webhook の
例は、webhook-id・webhook-timestamp・webhook-signature)webhookadmin、
早見表
| フレームワーク | 生の |
型 |
|---|---|---|
| Express | express.raw() をreq.body |
Buffer |
| Next.js |
await request.text() |
string |
| Next.js |
bodyParser: false に |
Buffer |
| Hono | await c.req.text() |
string |
| FastAPI | await request.body() |
bytes |
| Django | request.body |
bytes |
| Rails | request.raw_post |
String |
| Laravel | $request->getContent() |
string |
| Go |
io.ReadAll(r.Body) |
[]byte |
Express
body-parser のraw は、req.body にtype のapplication/octet-stream なので、application/json をlimit の
import express from 'express';
import { Webhook } from 'webhookadmin';
const wh = new Webhook(process.env.WEBHOOK_SECRET!);
const app = express();
// Webhook の経路を express.json() より前に置く
app.post('/webhooks', express.raw({ type: 'application/json', limit: '1mb' }), async (req, res) => {
try {
const event = await wh.verify(req.body, req.headers);
res.sendStatus(204);
} catch {
res.sendStatus(400);
}
});
app.use(express.json()); // ほかの経路用app.use(express.json()) がexpress.json() を
Next.js(App Router)
Route Handler はRequest をrequest.text() で
// app/webhooks/route.ts
import { Webhook } from 'webhookadmin';
const wh = new Webhook(process.env.WEBHOOK_SECRET!);
export async function POST(request: Request) {
const body = await request.text();
try {
const event = await wh.verify(body, request.headers);
return new Response(null, { status: 204 });
} catch {
return new Response('invalid signature', { status: 400 });
}
}request.json() をRequest からJSON.parse(body) かverify の
Next.js(Pages Router)
Pages Router のbodyParser をfalse に
// pages/api/webhooks.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { Webhook } from 'webhookadmin';
export const config = { api: { bodyParser: false } };
const wh = new Webhook(process.env.WEBHOOK_SECRET!);
async function readRaw(req: NextApiRequest): Promise<Buffer> {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
return Buffer.concat(chunks);
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const raw = await readRaw(req);
try {
await wh.verify(raw, req.headers);
res.status(204).end();
} catch {
res.status(400).end();
}
}Hono
Hono のc.req.text() はc.req.arrayBuffer() は
import { Hono } from 'hono';
import { Webhook } from 'webhookadmin';
const app = new Hono<{ Bindings: { WEBHOOK_SECRET: string } }>();
app.post('/webhooks', async (c) => {
const wh = new Webhook(c.env.WEBHOOK_SECRET); // Workers では c.env から読む
const body = await c.req.text();
try {
await wh.verify(body, c.req.raw.headers);
return c.body(null, 204);
} catch {
return c.text('invalid signature', 400);
}
});
export default app;検証のzValidator('json', …) など)
FastAPI
FastAPI のRequest はRequest で、await request.body() が
import os
from fastapi import FastAPI, Request, Response
from standardwebhooks.webhooks import Webhook
wh = Webhook(os.environ["WEBHOOK_SECRET"]) # whsec_…
app = FastAPI()
@app.post("/webhooks")
async def webhooks(request: Request):
body = await request.body() # bytes
try:
event = wh.verify(body, dict(request.headers))
except Exception:
return Response(status_code=400)
return Response(status_code=204)Django
HttpRequest.body はrequest.read() などでrequest.body はRawPostDataException に
import os
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from standardwebhooks.webhooks import Webhook
wh = Webhook(os.environ["WEBHOOK_SECRET"])
@csrf_exempt
@require_POST
def webhooks(request):
try:
event = wh.verify(request.body, dict(request.headers))
except Exception:
return HttpResponse(status=400)
return HttpResponse(status=204)Rails
request.raw_post はActionController::Base を
class WebhooksController < ApplicationController
protect_from_forgery except: :create
def create
webhook = StandardWebhooks::Webhook.new(ENV.fetch('WEBHOOK_SECRET'))
payload = webhook.verify(request.raw_post, {
'webhook-id' => request.headers['webhook-id'],
'webhook-timestamp' => request.headers['webhook-timestamp'],
'webhook-signature' => request.headers['webhook-signature'],
})
head :no_content
rescue StandardWebhooks::WebhookVerificationError
head :bad_request
end
endLaravel
Laravel のRequest はRequest をgetContent() がbootstrap/app.php のvalidateCsrfTokens(except: [...]) で
use Illuminate\Http\Request;
Route::post('/webhooks', function (Request $request) {
$body = $request->getContent();
$id = (string) $request->header('webhook-id');
$ts = (string) $request->header('webhook-timestamp');
if (!ctype_digit($ts) || abs(time() - (int) $ts) > 300) {
return response('', 400);
}
$key = base64_decode(substr(env('WEBHOOK_SECRET'), strlen('whsec_')));
$expected = base64_encode(hash_hmac('sha256', "{$id}.{$ts}.{$body}", $key, true));
foreach (explode(' ', (string) $request->header('webhook-signature')) as $part) {
[$version, $sig] = array_pad(explode(',', $part, 2), 2, '');
if ($version === 'v1' && hash_equals($expected, $sig)) {
return response('', 204);
}
}
return response('', 400);
});Go(net/http)
サーバーがr.Body はhttp.MaxBytesReader で
package main
import (
"io"
"net/http"
"os"
standardwebhooks "github.com/standard-webhooks/standard-webhooks/libraries/go"
)
func main() {
wh, err := standardwebhooks.NewWebhook(os.Getenv("WEBHOOK_SECRET"))
if err != nil {
panic(err)
}
http.HandleFunc("POST /webhooks", func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
http.Error(w, "too large", http.StatusRequestEntityTooLarge)
return
}
if err := wh.Verify(body, r.Header); err != nil {
http.Error(w, "invalid signature", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusNoContent)
})
http.ListenAndServe(":3000", nil)
}よくある落とし穴
- 全体に
JSON の 。parser を 掛けている Express の app.use(express.json())、NestJS の 既定の 設定、 Hono や FastAPI の バリデーターなど、 経路より 先に 本文を 読む 仕組みが あると、 生の 本文は 手に 入りません。 NestJS は NestFactory.create(AppModule, { rawBody: true })で起動すると req.rawBodyで受け取れます (NestJS の ドキュメント )。 - 文字列に
変換する 。ときに 中身が 変わる UTF-8 以外で 読む、 改行を 正規化する、 前後の 空白を 取り除く、 と いった 処理が 途中に 入ると 署名は 合いません。 bytes の まま 渡すか、 UTF-8 で そのまま 文字列にします。 - CSRF の
保護で 。拒否される Rails・Django・Laravel は、 フォームの 送信を 守る ために POST に CSRF の トークンを 求めます。 Webhook の 送る 側は トークンを 送れないので、 Webhook の 経路だけ削除します。 Stripe の ドキュメントも 同じ 注意を 書いています。
手元での確認方法
- 検証の
前に、 受け取った 本文の 長さと SHA-256 を 記録する。 - 送る
側の 配信の 記録や 手元の 送信の スクリプトで、 送った 本文の SHA-256 を 計算する。 - 2 つが
一致すれば、 生の 本文は 取得できています。 一致しなければ、 途中で 本文が 変換されています。 - 本文が
一致しているのに 検証が 失敗するなら、 鍵か 署名する 中身が 違います。 切り分けの 手順は署名検証が 失敗する に原因の 記事 まとめました。
手元の
受け側が
よくある質問
Next.js の App Router ではどう受け取りますか。
Route Handler で
Express で 1 つの経路だけ生の本文で受けるにはどうしますか。
その
Python では bytes と str のどちらを渡しますか。
受け取った