企业服务认证 API
用宿主管理的会话连接业务 API,让访问令牌留在宿主,而不是传入页面或模型。
按章节查看契约、签名、字段与示例;未注明的默认值不作推断。
本页内容
01声明业务资源
在 extension.json 顶层添加 authentication。下面地址是占位示例,必须替换为真实资源服务与 audience。baseUrl 要求 HTTPS、以 / 结尾,不能包含凭据、查询或 fragment。
"authentication": {
"resources": [{
"id": "business",
"title": "Business service",
"baseUrl": "https://api.example.com/v1/",
"audience": "https://api.example.com/",
"scopes": ["tasks.read"]
}]
}02配置身份提供方并登录
管理员需提供支持桌面公共客户端的 OAuth Code + PKCE S256 配置,并允许 http://127.0.0.1:{port}/callback 回调。在设置的账号区域配置 issuer/clientId。登录从 page operation 调用 invocation.authentication.requestSession(resourceId),该操作声明 timeoutMs: 120000。
03ExtensionAuthentication
在扩展后端通过 context.authentication 使用。Session 是不透明身份引用,不包含 access token。没有全局账号枚举器,当前也不提供 refresh token。
| 字段 / API | 说明 |
|---|---|
| getSession(resourceId): Promise<AuthenticationSession|null> | 静默读取已有会话。 |
| disconnect(resourceId): Promise<void> | 断开资源连接。 |
| onDidChangeSessions(listener): Disposable | 会话变化事件;加入 subscriptions。 |
| request({sessionId,path,method?,body?}) | 返回 Promise<{status,body,contentType}>,body 为字符串。 |
04请求范围与限制
path 在资源 baseUrl 前缀下解析:baseUrl 为 /v1/ 时,/tasks 请求 /v1/tasks。支持 GET/POST/PUT/PATCH/DELETE/HEAD;不允许任意 URL、请求头、Cookie 或重定向。请求体 JSON 字符串最多 256 KiB,响应最多 1 MiB,超时 30 秒。不自动重试;401 会使会话失效。
const session = await context.authentication.getSession('business');
if (!session) throw new Error('Sign in from the extension page first');
const response = await context.authentication.request({
sessionId: session.id, path: '/tasks', method: 'GET'
});
if (response.status !== 200) throw new Error('Business request failed');05Session 字段与隔离
AuthenticationSession 包含 id、resourceId、connectionId、account:{id,name}、scopes:string[]、expiresAt:number。会话绑定扩展、包版本、资源和连接。当前本地消息不按账号隔离;切换账号时应自行设计业务消息归属。
打开完整可运行案例