温馨提示:本站仅提供公开网络链接索引服务,不存储、不篡改任何第三方内容,所有内容版权归原作者所有
AI智能索引来源:http://www.bun.com/docs/runtime/csrf
点击访问原文链接

CSRF Protection - Bun

CSRF Protection - BunDocumentation Index

Fetch the complete documentation index at: /docs/llms.txt

Use this file to discover all available pages before exploring further.

Skip to main contentBun home pageSearch...⌘KInstall BunSearch...NavigationUtilitiesCSRF ProtectionRuntimePackage ManagerBundlerTest RunnerGuidesReferenceBlogFeedback:first-child]:!hidden peer-[.is-custom]:[&>:first-child]:sm:!hidden peer-[.is-custom]:[&>:first-child]:md:!hidden peer-[.is-custom]:[&>:first-child]:lg:!hidden peer-[.is-custom]:[&>:first-child]:xl:!hidden">Get StartedWelcome to BunInstallationQuickstartTypeScriptTypeScript 6 and 7bun initbun createCore RuntimeBun RuntimeWatch ModeDebuggingREPLbunfig.tomlFile & Module SystemFile TypesModule ResolutionJSXAuto-installPluginsFile System RouterHTTP serverServerRoutingCookiesTLSError HandlingMetricsNetworkingFetchWebSocketsTCPUDPDNSData & StorageCookiesFile I/OStreamsBinary DataArchiveSQLSQLiteS3RedisConcurrencyWorkersProcess & SystemEnvironment VariablesShellSpawnWebViewCronInterop & ToolingNode-APIFFIC CompilerTranspilerUtilitiesCSRF ProtectionSecretsConsoleTOMLYAMLMarkdownJSON5JSONLHTMLRewriterImageHashingGlobSemverColorUtilsStandards & CompatibilityGlobalsBun APIsWeb APIsNode.js CompatibilityContributingRoadmapBenchmarkingContributingBuilding WindowsBindgenLicenseOn this pageBun.CSRF.generate()Bun.CSRF.verify()Using with Bun.serve()Default secretTypeScriptUtilitiesCSRF ProtectionCopy pagespan]:line-clamp-1 overflow-hidden group flex items-center py-0.5 gap-1 text-sm text-gray-950/50 dark:text-white/50 group-hover:text-gray-950/70 dark:group-hover:text-white/70 rounded-none rounded-r-xl border px-3 border-gray-200 aspect-square dark:border-white/[0.07] bg-background-light dark:bg-background-dark hover:bg-gray-600/5 dark:hover:bg-gray-200/5" aria-label="More actions" type="button" id="radix-_R_n4ctdbsnlht5lebsnpfdb_" aria-haspopup="menu" aria-expanded="false" data-state="closed">*]:[overflow-wrap:anywhere]">

Generate and verify CSRF tokens with Bun’s built-in API

Copy pagespan]:line-clamp-1 overflow-hidden group flex items-center py-0.5 gap-1 text-sm text-gray-950/50 dark:text-white/50 group-hover:text-gray-950/70 dark:group-hover:text-white/70 rounded-none rounded-r-xl border px-3 border-gray-200 aspect-square dark:border-white/[0.07] bg-background-light dark:bg-background-dark hover:bg-gray-600/5 dark:hover:bg-gray-200/5" aria-label="More actions" type="button" id="radix-_R_1cctdbsnlht5lebsnpfdb_" aria-haspopup="menu" aria-expanded="false" data-state="closed">Bun provides a built-in API for generating and verifying CSRF (Cross-Site Request Forgery) tokens through Bun.CSRF. Tokens are signed with HMAC and include expiration timestamps to limit the token validity window. csrf.ts
// Generate a token bound to the requester's session
const token = Bun.CSRF.generate("my-secret", { sessionId: "user-session-id" });

// Verify it
const isValid = Bun.CSRF.verify(token, { secret: "my-secret", sessionId: "user-session-id" });
console.log(isValid); // true
Always pass a sessionId (the requester’s session identifier or user ID) to both generate() and verify(). Without it, a token is only bound to the secret — any token the server has ever issued validates for every user, so an attacker can obtain a token in their own session and replay it in a forged cross-site request from a victim’s browser. ​Bun.CSRF.generate() Generate a CSRF token. The token contains a cryptographic nonce, a timestamp, and an HMAC signature, encoded as a string. generate.ts
const token = Bun.CSRF.generate("my-secret-key");
Parameters: secret (string, optional) — The secret key used to sign the token. If not provided, Bun generates a random in-memory default secret (unique per thread). options (object, optional): OptionTypeDefaultDescriptionexpiresInnumber86400000Milliseconds until the token expires. Defaults to 24 hours.encodingstring"base64url"Token encoding format: "base64", "base64url", or "hex".algorithmstring"sha256"HMAC algorithm: "sha256", "sha384", "sha512", "sha512-256", "blake2b256", or "blake2b512".sessionIdstring(none)Binds the token to the requesting principal (session ID, user ID, or equivalent). The token will only verify when the same sessionId is passed to verify(). Returns: string — the encoded token. generate-options.ts
// Token bound to the requester's session that expires in 1 hour, encoded as hex
const token = Bun.CSRF.generate("my-secret", {
sessionId: "user-session-id",
expiresIn: 60 * 60 * 1000,
encoding: "hex",
});

// Using a different algorithm
const token2 = Bun.CSRF.generate("my-secret", {
sessionId: "user-session-id",
algorithm: "sha512",
});
​Bun.CSRF.verify() Verify a CSRF token. Returns true if the token is valid and has not expired, false otherwise. verify.ts
const isValid = Bun.CSRF.verify(token, { secret: "my-secret-key" });
Parameters: token (string, required) — The token to verify. options (object, optional): OptionTypeDefaultDescriptionsecretstring(auto)The secret used to sign the token. If not provided, uses the same in-memory default as generate().maxAgenumber86400000Maximum token age in milliseconds, independent of the token’s own expiresIn.encodingstring"base64url"Must match the encoding used during generate().algorithmstring"sha256"Must match the algorithm used during generate().sessionIdstring(none)Must match the sessionId used during generate(). A token bound to one principal fails verification for any other principal, and a token generated without a sessionId fails verification when one is supplied. Returns: boolean verify-options.ts
// Verify a token bound to the requester's session
const isValid = Bun.CSRF.verify(token, {
secret: "my-secret",
sessionId: "user-session-id",
});

// Enforce a shorter max age than what the token was generated with
const isValid2 = Bun.CSRF.verify(token, {
secret: "my-secret",
sessionId: "user-session-id",
maxAge: 60 * 1000, // reject tokens older than 1 minute
});
​Using with Bun.serve() A typical pattern is to generate a token when rendering a form, embed it in a hidden field, and verify it when the form is submitted. Pass the requester’s session identifier as sessionId to both calls so the token only works for the user it was issued to. server.ts
const SECRET = process.env.CSRF_SECRET || "my-secret";

// Resolve the requester's session identifier from a session cookie. Returns
// null when the visitor has no session yet — never fall back to a shared
// placeholder, or every session-less visitor would share one token binding.
function getSessionId(req: Request): string | null {
return req.headers.get("cookie")?.match(/(?:^|;\s*)session=([^;]+)/)?.[1] ?? null;
}

const server = Bun.serve({
routes: {
"/form": req => {
// Create a per-visitor session before issuing the form so the token is
// bound to this visitor and no one else.
let sessionId = getSessionId(req);
const headers = new Headers({ "Content-Type": "text/html" });
if (!sessionId) {
sessionId = crypto.randomUUID();
headers.append("Set-Cookie", `session=${sessionId}; HttpOnly; SameSite=Lax; Path=/`);
}

const token = Bun.CSRF.generate(SECRET, { sessionId });

return new Response(
`
${token}" />

Send
`,
{ headers },
);
},

"/submit": {
POST: async req => {
const sessionId = getSessionId(req);
const formData = await req.formData();
const csrfToken = formData.get("_csrf");

if (!sessionId || typeof csrfToken !== "string" || !Bun.CSRF.verify(csrfToken, { secret: SECRET, sessionId })) {
return new Response("Invalid CSRF token", { status: 403 });
}

return new Response("OK");
},
},
},
});

console.log(`Listening on ${server.url}`);
​Default secret If you omit the secret parameter in both generate() and verify(), Bun uses a random secret generated once per thread. This is convenient for single-thread applications but won’t work across multiple servers, workers, or after a restart. default-secret.ts
// Both calls use the same per-thread default secret within this runtime context.
const token = Bun.CSRF.generate();
const isValid = Bun.CSRF.verify(token); // true
For production use, always provide an explicit secret shared across your infrastructure. ​TypeScript types.ts
type CSRFAlgorithm = "blake2b256" | "blake2b512" | "sha256" | "sha384" | "sha512" | "sha512-256";

interface CSRFGenerateOptions {
expiresIn?: number;
encoding?: "base64" | "base64url" | "hex";
algorithm?: CSRFAlgorithm;
sessionId?: string;
}

interface CSRFVerifyOptions {
secret?: string;
encoding?: "base64" | "base64url" | "hex";
algorithm?: CSRFAlgorithm;
maxAge?: number;
sessionId?: string;
}

namespace Bun.CSRF {
function generate(secret?: string, options?: CSRFGenerateOptions): string;
function verify(token: string, options?: CSRFVerifyOptions): boolean;
}

Was this page helpful?

YesNoSuggest editsRaise issueTranspilerPreviousSecretsNext⌘IxgithubdiscordyoutubePowered byThis documentation is built and hosted on Mintlify, a developer documentation platform

CSRF Protection - Bun,AI智能索引,全网链接索引,智能导航,网页索引

    Generate and verify CSRF tokens with Bun