@auth0/auth0-fastify-api

中文文档
1.3.0发布于 2026/05/18MITTypeScriptESM + CJS构建来源已验证近 30 天下载 10.7万

Auth0 SDK for Fastify API's on JavaScript runtimes

原始使用文档
文档目录11 节
  1. Documentation
  2. Getting Started
  3. 1. Install the SDK
  4. 3. Register the Auth0 Fastify plugin for APIs
  5. DPoP (Demonstration of Proof-of-Possession)
  6. On-Behalf-Of Token Exchange
  7. Feedback
  8. Contributing
  9. Raise an issue
  10. Vulnerability Reporting
  11. What is Auth0?

The Auth0 Fastify-API SDK is a library for protecting API's in Fastify applications.

Release Downloads License

📚 Documentation - 🚀 Getting Started - 💬 Feedback

Documentation

  • Examples - examples for your different use cases.
  • Docs Site - explore our docs site and learn more about Auth0.

Getting Started

1. Install the SDK

npm i @auth0/auth0-fastify-api

This library requires Node.js 20 LTS and newer LTS versions.

3. Register the Auth0 Fastify plugin for APIs

Register the Auth0 fastify plugin for API's with the Fastify instance.

import fastifyAuth0Api from '@auth0/auth0-fastify-api';

const fastify = Fastify({
  logger: true,
});

fastify.register(fastifyAuth0Api, {
  domain: '<AUTH0_DOMAIN>',
  audience: '<AUTH0_AUDIENCE>',
});

The AUTH0_DOMAIN can be obtained from the Auth0 Dashboard once you've created an API. The AUTH0_AUDIENCE is the identifier of the API that is being called. You can find this in the API section of the Auth0 dashboard.

Protecting API Routes

In order to protect an API route, you can use the SDK's requireAuth() method in a preHandler:

fastify.register(() => {
  fastify.get(
    '/protected-api',
    {
      preHandler: fastify.requireAuth(),
    },
    async (request: FastifyRequest, reply) => {
      return `Hello, ${request.user.sub}`;
    }
  );
});

The SDK exposes the claims, extracted from the token, as the user property on the FastifyRequest object. In order to use a custom user type to represent custom claims, you can configure the Token type in a module augmentation:

declare module '@auth0/auth0-fastify-api' {
  interface Token {
    id: number;
    name: string;
    age: number;
  }
}

Doing so will change the user type on the FastifyRequest object automatically:

fastify.register(() => {
  fastify.get(
    '/protected-api',
    {
      preHandler: fastify.requireAuth(),
    },
    async (request: FastifyRequest, reply) => {
      return `Hello, ${request.user.name}`;
    }
  );
});

[!IMPORTANT]
The above is to protect API routes by the means of a bearer token, and not server-side rendering routes using a session.

DPoP (Demonstration of Proof-of-Possession)

DPoP binds access tokens to a specific client's key pair, preventing stolen tokens from being replayed by attackers. The SDK supports DPoP with three modes:

  • allowed (default): accepts both Bearer and DPoP-bound tokens.
  • required: only DPoP-bound tokens are accepted; Bearer tokens are rejected.
  • disabled: DPoP is ignored; Bearer-only behavior.
import fastifyAuth0Api from '@auth0/auth0-fastify-api';

const fastify = Fastify({ logger: true });

fastify.register(fastifyAuth0Api, {
  domain: '<AUTH0_DOMAIN>',
  audience: '<AUTH0_AUDIENCE>',
  dpop: { mode: 'required' },
});

When DPoP is enabled, clients send:

  1. An Authorization: DPoP <access_token> header (instead of Bearer).
  2. A DPoP header containing a proof JWT tied to the request method and URL.

The SDK automatically extracts the DPoP proof from the request, validates it against the access token's cnf.jkt claim, and verifies that the proof matches the current HTTP method and URL.

For the full configuration reference and error handling details, see the DPoP section in EXAMPLES.md.

On-Behalf-Of Token Exchange

Use fastify.auth0Client.getTokenOnBehalfOf() when your Fastify API needs to call a downstream API on behalf of the same user, such as in an MCP server. The method exchanges the incoming access token for a new one scoped to the downstream API while preserving the user's identity.

getTokenOnBehalfOf() requires a confidential client. Register the plugin with clientId and clientSecret (or clientAssertionSigningKey for client assertion authentication).

import fastifyAuth0Api from '@auth0/auth0-fastify-api';

const fastify = Fastify({ logger: true });

fastify.register(fastifyAuth0Api, {
  domain: '<AUTH0_DOMAIN>',
  audience: '<AUTH0_AUDIENCE>',
  clientId: '<AUTH0_CLIENT_ID>',
  clientSecret: '<AUTH0_CLIENT_SECRET>',
});

fastify.register(() => {
  fastify.post(
    '/schedule-meeting',
    {
      preHandler: fastify.requireAuth(),
    },
    async (request: FastifyRequest) => {
      // request.getToken() returns the raw JWT without the `Bearer ` prefix.
      const obo = await fastify.auth0Client!.getTokenOnBehalfOf(request.getToken()!, {
        audience: 'https://calendar-api.example.com',
        scope: 'calendar:read calendar:write',
      });

      const response = await fetch('https://calendar-api.example.com/meetings', {
        method: 'POST',
        headers: { authorization: `Bearer ${obo.accessToken}` },
        body: JSON.stringify(request.body),
      });

      return response.json();
    }
  );
});

For a full walkthrough including error handling, act claim inspection, and the downstream verifier pattern, see the On-Behalf-Of Token Exchange section in EXAMPLES.md.

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please read the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

What is Auth0?

Auth0 Logo

Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?

This project is licensed under the MIT license. See the LICENSE file for more info.

版本与发布记录

@auth0/auth0-fastify-api 共发布 7 个版本,首次发布于 2025/03/28;过去 12 个月发布了 2 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.3.0latest2026/05/185 个月前
1.2.02026/04/106 个月前
1.1.02025/10/021.1 年前
1.0.32025/09/021.2 年前
1.0.22025/06/051.4 年前
1.0.12025/03/291.6 年前

关于 @auth0/auth0-fastify-api 的常见问题

@auth0/auth0-fastify-api 是什么?

Auth0 SDK for Fastify API's on JavaScript runtimes

如何安装 @auth0/auth0-fastify-api?

在项目目录运行 npm install @auth0/auth0-fastify-api,或使用 pnpm add / yarn add / bun add。

@auth0/auth0-fastify-api 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@auth0/auth0-fastify-api 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@auth0/auth0-fastify-api 可以商用吗?

@auth0/auth0-fastify-api 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@auth0/auth0-fastify-api 的下载量有多少?

根据 npm 官方下载统计,@auth0/auth0-fastify-api 在 2026/10/07 – 2026/11/05 这 30 天内被下载 107,049 次,日均约 3,568 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@auth0/auth0-fastify-api 还在维护吗?

最新版本 1.3.0 发布于 2026/05/18(5 个月前);至今共发布 7 个版本,其中过去 12 个月发布了 2 个;首次发布于 2025/03/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。