> ## Documentation Index
> Fetch the complete documentation index at: https://auth0.com/llms.txt
> Use this file to discover all available pages before exploring further.

# ユーザーアカウントのリンクを解除する

> Management APIのUnlink a User Account（ユーザーアカウントのリンクを解除する）エンドポイントを使用して、ターゲットのユーザーアカウントからIDのリンクを解除して、分離したユーザーアカウントに戻す方法を説明します。

export const AuthCodeBlock = ({filename, icon, language, highlight, children}) => {
  const [displayText, setDisplayText] = useState(children);
  const [copyText, setCopyText] = useState(children);
  const wrapperRef = React.useRef(null);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      if (!window.autorun || !window.rootStore) {
        return;
      }
      unsubscribe = window.autorun(() => {
        let processedChildrenForDisplay = children;
        let processedChildrenForCopy = children;
        for (const [key, value] of window.rootStore.variableStore.values.entries()) {
          const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
          let displayValue = value;
          if (key === "{yourClientSecret}" && value !== "{yourClientSecret}") {
            displayValue = value.substring(0, 3) + "*****MASKED*****";
          }
          processedChildrenForDisplay = processedChildrenForDisplay.replaceAll(new RegExp(escapedKey, "g"), displayValue);
          processedChildrenForCopy = processedChildrenForCopy.replaceAll(new RegExp(escapedKey, "g"), value);
        }
        setDisplayText(processedChildrenForDisplay);
        setCopyText(processedChildrenForCopy);
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  useEffect(() => {
    if (!wrapperRef.current) return;
    const originalWriteText = navigator.clipboard.writeText.bind(navigator.clipboard);
    let isOverriding = false;
    const handleClick = e => {
      const button = e.target.closest('[data-testid="copy-code-button"]');
      if (!button || !wrapperRef.current.contains(button)) return;
      isOverriding = true;
      navigator.clipboard.writeText = text => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
          return originalWriteText(copyText);
        }
        return originalWriteText(text);
      };
      setTimeout(() => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
        }
      }, 100);
    };
    const wrapper = wrapperRef.current;
    wrapper.addEventListener('click', handleClick, true);
    return () => {
      wrapper.removeEventListener('click', handleClick, true);
      if (navigator.clipboard.writeText !== originalWriteText) {
        navigator.clipboard.writeText = originalWriteText;
      }
    };
  }, [copyText]);
  return <div ref={wrapperRef}>
      <CodeBlock filename={filename} icon={icon} language={language} lines highlight={highlight}>
        {displayText}
      </CodeBlock>
    </div>;
};

Auth0 <Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=management-api" tip="Management API: 顧客が管理タスクを実行できるようにするための製品。" cta="用語集の表示">Management API</Tooltip>の[Unlink a User Account](/docs/ja-jp/api/management/v2#!/Users/delete_user_identity_by_user_id)（ユーザーアカウントのリンクを解除する）エンドポイント、またはAuth0.jsライブラリーを使用して、ターゲットのユーザーアカウントからIDのリンクを解除して、分離したユーザーアカウントに戻します。

このリンク解除プロセスの結果は次のようになります。

* プライマリアカウントのID配列からセカンダリアカウントが削除されます。
* 新たなセカンダリユーザーアカウントが作成されます。
* セカンダリアカウントにメタデータはありません。

セカンダリIDを完全に削除したい場合は、先にアカウントのリンクを解除して、次に、[新たに作成されたセカンダリアカウントを削除](/docs/ja-jp/manage-users/user-accounts/delete-users)しなければなりません。

エンドポイントを呼び出す場所に応じて、次の2つのスコープのいずれかを使用します。

* [クライアント側コード](/docs/ja-jp/manage-users/user-accounts/user-account-linking/user-initiated-account-linking-client-side-implementation)からの場合は`update:current_user_identities`
* [サーバー側コード](/docs/ja-jp/manage-users/user-accounts/user-account-linking/suggested-account-linking-server-side-implementation)からの場合は`update:users`

このエンドポイントでは、以下のパラメーターを使用します。

| パラメーター     | タイプ      | 説明                                                                                                  |
| ---------- | -------- | --------------------------------------------------------------------------------------------------- |
| `id`       | `string` | プライマリユーザーアカウントのID（必須）                                                                               |
| `provider` | `string` | リンクされたセカンダリアカウントのIDプロバイダー名（`google-oauth2`など）                                                       |
| `user_id`  | `string` | リンクされたセカンダリアカウントのID（`google-oauth2\|123456789081523216417`の`\|`の後に表示された`123456789081523216417`部分など） |

インスタンスに複数のプロバイダーからのユーザーがある場合は、`user_id`の前に`[connection_name]|`を入れて、プロバイダーの名前を付けることもできます（例：`"user-id":"google-oauth2|123456789081523216417"）`。

## 応答例

```javascript lines theme={null}
[
  {
    "connection": "Initial-Connection",
    "user_id": "5457edea1b8f22891a000004",
    "provider": "auth0",
    "isSocial": false,
    "access_token": "",
    "profileData": {
      "email": "",
      "email_verified": false,
      "name": "",
      "username": "johndoe",
      "given_name": "",
      "phone_number": "",
      "phone_verified": false,
      "family_name": ""
    }
  }
]
```

## プライマリアカウントからJWTを使用する

アカウントのリンクを解除するには、認可用のプライマリアカウントから<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-3" href="/docs/ja-jp/glossary?term=json-web-token" tip="JSON Web Token（JWT）: 二者間のクレームを安全に表現するために使用される標準IDトークン形式（および多くの場合、アクセストークン形式）。" cta="用語集の表示">JWT</Tooltip>を使用してManagement APIの[Unlink a User Accountエンドポイント](/docs/ja-jp/api/v2#!/Users/delete_user_identity_by_user_id)を呼び出します。

export const codeExample1 = `function unlinkAccount(secondaryProvider, secondaryUserId){
  var primaryUserId = localStorage.getItem('user_id');
  var primaryJWT = localStorage.getItem('id_token');
  $.ajax({
    type: 'DELETE',
    url: 'https://' + '{yourDomain}' + '/api/v2/users/' + primaryUserId +
         '/identities/' + secondaryProvider + '/' + secondaryUserId,
    headers: {
      'Authorization': 'Bearer ' + primaryJWT
    }
  }).then(function(identities){
    alert('unlinked!');
    showLinkedAccounts(identities);
  }).fail(function(jqXHR){
    alert('Error unlinking Accounts: ' + jqXHR.status + ' ' + jqXHR.responseText);
  });
}`;

<AuthCodeBlock children={codeExample1} language="javascript" />

## update:usersスコープを持つアクセストークンを使用する

2つ以上のユーザーアカウントのリンクを解除する必要がある場合は、`update:users`スコープを持つ[Management APIのアクセストークン](/docs/ja-jp/api/v2/tokens)を使用して、Management APIの[Unlink a User Accountエンドポイント](/docs/ja-jp/api/v2#!/Users/delete_user_identity_by_user_id)を呼び出します。

```javascript lines theme={null}
function unlinkAccount(secondaryProvider, secondaryUserId) {
  var primaryUserId = localStorage.getItem('user_id');
  var primaryAccessToken = localStorage.getItem('access_token');

  // Uses the Access Token of the primary user as a bearer token to identify the account
  // which will have the account unlinked to, and the user id of the secondary user, to identify
  // the user that will be unlinked from the primary account.

  $.ajax({
    type: 'DELETE',
    url: 'https://' + AUTH0_DOMAIN +'/api/v2/users/' + primaryUserId +
         '/identities/' + secondaryProvider + '/' + secondaryUserId,
    headers: {
      'Authorization': 'Bearer ' + primaryAccessToken
    }
  }).then(function(identities){
    alert('unlinked!');
    showLinkedAccounts(identities);
  }).fail(function(jqXHR){
    alert('Error unlinking Accounts: ' + jqXHR.status + ' ' + jqXHR.responseText);
  });
}
```

## サーバー側コードからアカウントのリンクを解除する

1. セッション内のユーザーを（それぞれが独立したユーザーアカウントを表す）新しいID配列で更新します。

```javascript lines theme={null}
const ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn();
const Auth0Client = require('../Auth0Client');
const express = require('express');
const router = express.Router();
...
router.post('/unlink-accounts/:targetUserProvider/:targetUserId',ensureLoggedIn, (req,res,next) => {
  Auth0Client.unlinkAccounts(req.user.id, req.params.targetUserProvider, req.params.targetUserId)
  .then( identities => {
    req.user.identities = req.user._json.identities = identities;
    res.send(identities);
  })
  .catch( err => {
    console.log('Error unlinking accounts!',err);
    next(err);
  });
});
```

1. `update:users`スコープを持つ[Management APIのアクセストークン](/docs/ja-jp/api/v2/tokens)を使用して、Management API v2の[Unlink a User Accountエンドポイント](/docs/ja-jp/api/v2#!/Users/delete_user_identity_by_user_id)を呼び出します。

export const codeExample2 = `const request = require('request');

class Auth0Client {
  ...
  unlinkAccounts(rootUserId, targetUserProvider, targetUserId){
    return new Promise((resolve,reject) => {
      var reqOpts = {
        method: 'DELETE',
        url: 'https://{yourDomain}/api/v2/users/' + rootUserId +
            '/identities/' + targetUserProvider + '/' + targetUserId,
        headers: {
          'Authorization': 'Bearer ' + process.env.AUTH0_APIV2_TOKEN
        }
      };
      request(reqOpts,(error, response, body) => {
        if (error) {
          return reject(error);
        } else if (response.statusCode !== 200) {
          return reject('Error unlinking accounts. Status: '+ response.statusCode + ' ' + JSON.stringify(body));
        } else {
          resolve(JSON.parse(body));
        }
      });
    });
  }
}

module.exports = new Auth0Client();`;

<AuthCodeBlock children={codeExample2} language="javascript" />

## もっと詳しく

* [ユーザーアカウントをリンクする](/docs/ja-jp/manage-users/user-accounts/user-account-linking/link-user-accounts)
* [ユーザーアカウントのリンク：サーバー側実装](/docs/ja-jp/manage-users/user-accounts/user-account-linking/suggested-account-linking-server-side-implementation)
* [ユーザー起点のアカウントのリンク：クライアント側実装](/docs/ja-jp/manage-users/user-accounts/user-account-linking/user-initiated-account-linking-client-side-implementation)
