# 联合凭据管理（FedCM）

> 说明依赖方如何通过 FedCM 请求 IdentityCredential、检测支持情况、处理策略与请求失败，并保留回退登录路径。

联合凭据管理 API 让依赖方请求浏览器居中协调身份提供方的登录。依赖方使用 `identity` 请求调用 `navigator.credentials.get()`；请求成功后返回携带提供方令牌的 `IdentityCredential`（[FedCM API](https://www.w3.org/TR/fedcm/)，W3C）。

## 支持情况

BCD 将 Chrome 108 记为 `IdentityCredential` 的首个支持版本。Android 版 Chrome 和 Edge 继承这项数据；Opera、Samsung Internet 和 Meta Quest Browser 也有支持记录。

Firefox、Safari 和 Android WebView 均记为不支持。FedCM 因而尚未达到 Baseline（BCD `api.IdentityCredential`；[FedCM API](https://developer.mozilla.org/en-US/docs/Web/API/FedCM_API)，MDN）。

## 语法

```js
const credential = await navigator.credentials.get({
  identity: {
    providers: [{
      configURL: 'https://idp.example/fedcm.json',
      clientId: 'rp-client-id',
    }],
  },
});
```

浏览器获取提供方配置及相关身份提供方端点，协调其账户界面，并把凭据返回给依赖方。FedCM 是安全上下文 API，经凭据管理 API 暴露在 `Window` 上（[Browser API](https://www.w3.org/TR/fedcm/#browser-api)，W3C）。

| 表达式 | 值 |
|---|---|
| `navigator.credentials.get(options)` | 居中协调的请求成功后，Promise 返回 `IdentityCredential` |
| `options.identity.providers` | 本次请求可用的身份提供方配置 |
| `credential.token` | 所选身份提供方生成的令牌 |
| `credential.isAutoSelected` | 浏览器是否在界面流程中自动选择了凭据 |

## 参数

`identity.providers` 是提供方配置序列。W3C 示例使用的核心字段是 `configURL` 和 `clientId`：前者标识提供方配置，后者向该提供方标识依赖方。按照规范，请求还可以携带 `nonce`、`loginHint` 和 `domainHint` 等值。

| 成员 | 必填 | 用途 |
|---|---|---|
| `configURL` | 是 | 给出身份提供方配置文件的完整 URL |
| `clientId` | 是 | 给出身份提供方签发给依赖方的标识符 |
| `nonce` | 否 | 把依赖方提供的值传给身份提供方 |
| `loginHint` | 否 | 筛选账户数据中登录提示相符的账户 |
| `domainHint` | 否 | 筛选账户数据中域提示相符的账户 |

返回的 `IdentityCredential` 带有身份提供方给出的 `token`。规范定义 `isAutoSelected`，用于报告浏览器在界面流程中是否自动选择了凭据（[IdentityCredential interface](https://www.w3.org/TR/fedcm/#browser-api-identity-credential-interface)，W3C）。

调用前，身份提供方需要准备 FedCM 规定的配置和端点。Chrome 的依赖方指南还要求：页面使用限制性的内容安全策略 `connect-src` 时，必须放行提供方配置列出的端点（[在依赖方实现 FedCM](https://developer.chrome.com/docs/identity/fedcm/implement/relying-party)，Chrome for Developers）。

## 异常

- 被 `identity-credentials-get` 权限策略阻止的文档会得到以 `NotAllowedError` 拒绝的 Promise。此特性的默认允许列表是 `self`；跨源 iframe 需要显式设置 `allow="identity-credentials-get"`（[Permissions Policy integration](https://www.w3.org/TR/fedcm/#permissions-policy-integration)，W3C）。
- 规范把提供方请求失败和没有符合条件的账户映射为 `NetworkError`。`identity-credentials-get` 策略拦截请求时返回 `NotAllowedError`，`configURL` 无效时返回 `InvalidStateError`（[Create an IdentityCredential](https://www.w3.org/TR/fedcm/#create-an-identitycredential)，W3C）。
- FedCM 需要身份提供方配合，依赖方无法独立部署。不支持 FedCM 时，第一个示例会显示网站现有登录路由。

异常名称只能指出一类故障，不能代替完整诊断。不支持 FedCM、返回空结果、权限策略拒绝或提供方请求失败后，都应让普通登录路由保持可用。下面的代码显示 `DOMException.name`，并保留标准登录链接，不会把特性检测结果当成提供方交换必定成功的证据。

:::caution
并发 FedCM 请求在 Chromium 中以 `NotAllowedError: Only one navigator.credentials.get request may be outstanding at one time.` 拒绝。这个确切字符串定义在 Chromium 的 [`authentication_credentials_container.cc`](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/modules/credentialmanagement/authentication_credentials_container.cc) 中（chromium.googlesource.com）。
:::

## 示例

运行代码前，请替换示例中的提供方 URL、客户端 ID、`/session/fedcm` 会话端点和回退 URL，并先配置身份提供方端点。页面还需由安全上下文提供。状态区中的文字来自代码分支，只是说明性输出，不代表浏览器实测结果。

### 请求凭据并提供回退

同时检测凭据管理容器和 `IdentityCredential`。任一对象不存在，或居中协调的请求没有返回令牌时，继续使用网站已有的登录路由。Chrome 的依赖方指南也用 `IdentityCredential` 检测功能，并要求不支持时改用其他身份方案（[在依赖方实现 FedCM](https://developer.chrome.com/docs/identity/fedcm/implement/relying-party)，Chrome for Developers）。

```html
<button id="federated-sign-in" type="button">使用身份提供方登录</button>
<a id="sign-in-fallback" href="/sign-in" hidden>使用标准登录页</a>
<p id="sign-in-status" role="status"></p>

<script type="module">
const button = document.querySelector('#federated-sign-in');
const fallback = document.querySelector('#sign-in-fallback');
const status = document.querySelector('#sign-in-status');

function useFallback(message) {
  status.textContent = message;
  fallback.hidden = false;
}

async function sendTokenToServer(token) {
  const response = await fetch('/session/fedcm', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ token }),
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
}

async function signIn() {
  if (!('credentials' in navigator) || !('IdentityCredential' in window)) {
    useFallback('FedCM 不可用，请使用标准登录页。');
    return;
  }

  try {
    const credential = await navigator.credentials.get({
      identity: {
        providers: [{
          configURL: 'https://idp.example/fedcm.json',
          clientId: 'rp-client-id',
        }],
      },
    });

    if (!credential?.token) {
      useFallback('未返回凭据，请使用标准登录页。');
      return;
    }
    await sendTokenToServer(credential.token);
    status.textContent = '凭据已发送到服务器。';
  } catch (error) {
    useFallback(`FedCM 未完成：${error.name}`);
  }
}

button.addEventListener('click', signIn);
</script>
```

这段代码定义了所引用的全部元素和辅助函数。请把不透明令牌发给依赖方服务器验证。`IdentityCredential` 存在不代表某个提供方已经配置好，也不代表请求必然成功。任何分支调用 `useFallback()` 后，状态区会说明情况，普通 `/sign-in` 链接也会显示出来。

### 避免并发请求失败

Chromium 同一时间允许一个未完成的 FedCM `navigator.credentials.get()` 请求。Promise 等待期间禁用启动按钮，并在 `finally` 中恢复；请求被拒绝时显示普通登录链接。上面的警告框给出了 Chromium 对并发请求返回的确切异常。

```html
<button id="fedcm-once" type="button">使用 FedCM 继续</button>
<a id="ordinary-sign-in" href="/sign-in" hidden>使用标准登录页</a>
<p id="fedcm-result" role="status"></p>

<script type="module">
const button = document.querySelector('#fedcm-once');
const fallback = document.querySelector('#ordinary-sign-in');
const result = document.querySelector('#fedcm-result');

button.addEventListener('click', async () => {
  button.disabled = true;
  try {
    const credential = await navigator.credentials.get({
      identity: { providers: [{
        configURL: 'https://idp.example/fedcm.json',
        clientId: 'rp-client-id',
      }] },
    });
    result.textContent = credential?.token
      ? 'FedCM 返回了令牌。'
      : 'FedCM 未返回令牌。';
    fallback.hidden = Boolean(credential?.token);
  } catch (error) {
    result.textContent = `FedCM 失败：${error.name}`;
    fallback.hidden = false;
  } finally {
    button.disabled = false;
  }
});
</script>
```

按钮禁用期间，用户再次点击不会启动第二个请求。浏览器因其他文档列出的原因拒绝请求时，`catch` 分支会显示异常名称并露出 `/sign-in`。如果站点有多个 FedCM 启动入口，还需让这些入口共享同一个等待状态，才能采用相同的恢复路径。

## 另请参阅

- [凭据管理 API](/zh/reference/capabilities/credential-management/)
- [WebAuthn 与通行密钥](/zh/reference/capabilities/webauthn-passkeys/)
- [浏览器兼容性数据](/zh/compatibility/)
- [Federated Credential Management API](https://www.w3.org/TR/fedcm/)（w3.org）
- [Implement an identity solution with FedCM on the relying-party side](https://developer.chrome.com/docs/identity/fedcm/implement/relying-party)（Chrome for Developers）