Better Auth Agent Auth 插件如何为 AI 代理提供服务发现、注册与能力授权
2026/9/18 21:42:11 网站建设 项目流程

Better Auth Agent Auth 插件如何为 AI 代理提供服务发现、注册与能力授权

【免费下载链接】better-authThe most comprehensive authentication framework项目地址: https://gitcode.com/GitHub_Trending/be/better-auth

如果你已经有一个基于 Better Auth 的服务端,想让它直接对 AI 代理开放:代理能发现你的服务能力、注册自己、经用户批准后在授权范围内调用接口,@better-auth/agent-auth插件就是做这件事的。它让你的 Better Auth 服务端充当 Agent Auth provider(服务端实现了 Agent Auth Protocol),代理通过服务发现文档拿到端点信息,注册后请求能力授权(grants),再使用短期签名的 JWT 执行有范围的 capability。注意官方文档的提醒:该插件是对一个仍在重度开发中的标准的实现,尚未稳定,未来可能有变动。

安装插件

先在项目中安装服务端插件包:

npm install @better-auth/agent-auth

文档还列出两个可选包(客户端与 CLI):

npm install @auth/agent @auth/agent-cli

在 auth 配置中声明 capabilities 与 onExecute

插件的核心配置是两部分:你的服务对外暴露哪些 capability,以及执行这些 capability 的onExecute处理函数。一个 capability 由namedescription和可选的 JSON Schemainput组成。

import { betterAuth } from "better-auth"; import { agentAuth } from "@better-auth/agent-auth"; export const auth = betterAuth({ plugins: [ agentAuth({ providerName: "Acme", providerDescription: "Acme project and deployment APIs for AI agents.", modes: ["delegated", "autonomous"], capabilities: [ { name: "deploy_project", description: "Deploy a project to production.", input: { type: "object", properties: { projectId: { type: "string" }, }, required: ["projectId"], }, }, { name: "list_projects", description: "List projects the current user can access.", }, ], async onExecute({ capability, arguments: args, agentSession }) { switch (capability) { case "list_projects": return [{ id: "proj_123", name: "marketing-site" }]; case "deploy_project": return { ok: true, projectId: args?.projectId, requestedBy: agentSession.user.id, }; default: throw new Error(`Unsupported capability: ${capability}`); } }, }), ], });

关于onExecute的适用边界要记清楚:它只处理走默认执行 URL(发现文档里的default_location)的调用;如果某个 capability 设置了自定义location,代理会直接调用那个 URL,onExecute不会被执行。文档建议用 capability 暴露窄范围、可审查的动作,而不是宽泛的 API 访问。

暴露服务发现文档

插件提供auth.api.getAgentConfiguration(),你需要把它挂到应用根目录的/.well-known/agent-configuration(Next.js 的写法如下):

import { auth } from "@/lib/auth"; import { NextResponse } from "next/server"; export async function GET() { const configuration = await auth.api.getAgentConfiguration(); return NextResponse.json(configuration); }

即使你的 Better Auth base path 是/api/auth,这个发现路由也要放在/.well-known/agent-configuration。发现文档里对执行最关键的三个字段:

  • issuer— provider 的基础 URL(即 Better Auth 的baseURL);
  • endpoints— 各路由的绝对 URL,例如execute指向该 base 下的POST /capability/execute
  • default_location— 默认执行端点的完整 URL,始终与endpoints.execute一致。capability 没有自定义 URL 时,代理用它作为 JWT 的aud,也用它作为请求 URL。

验证方式:直接向/.well-known/agent-configuration发 GET 请求,返回的 JSON 就是代理用来交互的全部端点信息。

迁移数据库

插件需要 agent、host、grant 和 approval 表。迁移方式二选一:

npx auth migrate

或者生成 schema 后自行应用:

npx auth generate

代理注册与能力授权流程

文档描述的标准流程是:

  1. 代理从/.well-known/agent-configuration发现你的 provider;
  2. 代理列出 capabilities,决定需要哪些;
  3. 代理在你的服务端注册并请求 capability grants;
  4. 用户通过 device authorization 或 CIBA 批准请求;
  5. 代理用短期签名 JWT(aud匹配所调用的 URL)在default_location或 capability 自己的location上调用每个已授权能力。

批准方法默认device_authorizationciba都启用,可用approvalMethodsresolveApprovalMethod限制或定制:

agentAuth({ approvalMethods: ["ciba", "device_authorization"], resolveApprovalMethod: ({ preferredMethod, supportedMethods }) => { if (preferredMethod && supportedMethods.includes(preferredMethod)) { return preferredMethod; } return "device_authorization"; }, deviceAuthorizationPage: "/device/capabilities", });

两个容易踩的点:

  • 插件不会替你渲染设备授权审批页面,deviceAuthorizationPage指向的页面必须由你的应用自己提供;
  • 如果想控制哪些能力自动授予新注册的 host,可以用defaultHostCapabilities(传true表示全部、单个 HTTP 方法字符串、方法数组,或接收完整运行时上下文的回调);allowDynamicHostRegistration控制是否允许未知 host 动态注册。

执行能力:grant 校验与自定义 location

默认路径(无location:代理向default_locationPOST{ capability, arguments }。插件依次验证 JWT(包括aud)、附加agentSession、检查 grant,然后调用你的onExecute

JWT 的aud规则

  • capability 没有自定义location时,auddefault_location/endpoints.execute,或插件已允许的 issuer / base URL;
  • 设置了location时,aud应是该绝对 URL(GET /capability/list在有location时也会返回它);配置中非法的location会在启动时报错;
  • capabilities恰好只列一个 id 时,aud也可以等于该 capability 的location;列了多个 capability 时,不接受各 capability 的location作为aud,应使用 issuer、base path 或默认执行端点;
  • 反代后面如需让Host/X-Forwarded-Protoaud校验对齐,设置trustProxy(默认false)。

自定义location路径:代理仍然带Authorization: Bearer头发送 agent JWT,你在自己的路由里解析会话。两个等价入口任选其一:auth.api.getAgentSession({ headers })在进程内完成校验(签名、audjti防重放、过期、请求绑定声明),返回AgentSessionnullverifyAgentRequest(request, auth)则把Request的 headers 转发到GET /agent/session

import { auth } from "@/lib/auth"; export async function POST(request: Request) { const agentSession = await auth.api.getAgentSession({ headers: request.headers, }); if (!agentSession) { return new Response("Unauthorized", { status: 401 }); } // Check grants, enforce constraints, run your handler… }

拿到agentSession后检查 grant——agentSession.agent.capabilityGrants是数据库中有效的 grants 与 JWTcapabilities声明的交集:

const CAP = "create_issue"; const allowed = agentSession.agent.capabilityGrants.some( (g) => g.capability === CAP && g.status === "active", ); if (!allowed) { return new Response("Forbidden", { status: 403 }); }

注意:如果该 grant 带有constraints,要在自定义路由里按POST /capability/execute相同的方式校验请求体或 query——插件不会在任意路由上重跑 execute 的约束校验,这段逻辑留在你的 handler 里(或抽成与onExecute共享的代码)。

agentSession上可用的字段:agentSession.user(delegated host 用户或resolveAutonomousUser解析出的用户)、agentSession.agent(id、name、mode、capabilityGrants、host id、metadata)、agentSession.host(代理链接到 host 时的 host 记录)。类型从@better-auth/agent-auth导出(如AgentSession)。

可选路径:用 OpenAPI 规范自动生成

如果你的服务已有 OpenAPI 3.x 规范,createFromOpenAPI可以直接生成插件需要的全部内容:capabilities(每个带operationId的 operation 变成一个同名 capability)、输入/输出 JSON Schema(path/query/header 参数加 JSON 请求体合并为input,200/201 响应体作为output)、代理onExecute,并可选地从infoproviderName/providerDescription

import { betterAuth } from "better-auth"; import { agentAuth } from "@better-auth/agent-auth"; import { createFromOpenAPI } from "@better-auth/agent-auth/openapi"; const spec = await fetch("https://api.example.com/openapi.json").then((r) => r.json(), ); export const auth = betterAuth({ plugins: [ agentAuth({ ...createFromOpenAPI(spec, { baseUrl: "https://api.example.com", }), }), ], });

其中api.example.com替换为你自己的 API 地址与规范地址。常用选项:

  • resolveHeaders— 代理 handler 代表代理调用你的上游 API,用它注入每次请求需要的凭据(例如从agentSession查出用户级 access token 后放入Authorization头);
  • defaultHostCapabilities— 控制自动授予新 host 的能力,如["GET", "HEAD"]
  • approvalStrength— 按 HTTP 方法映射批准强度,例如GET: "session"POST/PUT/DELETE: "webauthn",让写操作要求更强的用户验证;
  • location— 所有派生 capability 都带上该 URL,代理直接带着 agent JWT 打真实 API URL,由你自己的中间件处理会话,而不是走onExecute代理。

如果只需要管线的一部分,还有两个低层 helper:fromOpenAPI(spec)只返回Capability[]createOpenAPIHandler(spec, opts)只返回onExecute代理 handler,方便搭配手写 capabilities 使用。

import { fromOpenAPI, createOpenAPIHandler, } from "@better-auth/agent-auth/openapi"; const capabilities = fromOpenAPI(spec); const onExecute = createOpenAPIHandler(spec, { baseUrl: "https://api.example.com", }); agentAuth({ capabilities, onExecute });

客户端插件与事件审计(可选)

需要类型安全地访问插件端点时,在 Better Auth 客户端里加上客户端插件:

import { createAuthClient } from "better-auth/client"; import { agentAuthClient } from "@better-auth/agent-auth/client"; export const authClient = createAuthClient({ plugins: [ agentAuthClient(), ], });

审计方面,onEvent回调会捕获生命周期事件:agent 创建与吊销、host 创建与登记、capability 请求与批准、capability 执行。文档指出这是写审计日志或接入分析管线的合适位置。

完成后的验证方式与限制

按上面的顺序做完后,可以按以下方式核对:

  1. GET/.well-known/agent-configuration,确认返回的发现文档包含issuerendpointsdefault_location
  2. 走一遍代理流程后,自定义路由中auth.api.getAgentSession({ headers })返回非nullAgentSession即代表 JWT 校验通过,返回null则按文档示例响应 401;
  3. 未获批的能力调用时,capabilityGrants中没有status === "active"的匹配项,按文档示例响应 403。

限制方面:插件明确标注为不稳定实现;设备审批页面需要你的应用自行提供;capability 设置了locationonExecute不生效,约束校验也转移到你的 handler。更多配置项(requireAuthForCapabilitiesresolveCapabilities过滤可见能力等)见仓库中的 Agent Auth 插件文档。

【免费下载链接】better-authThe most comprehensive authentication framework项目地址: https://gitcode.com/GitHub_Trending/be/better-auth

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询