> ## Documentation Index
> Fetch the complete documentation index at: https://docs-staging-feat-docs-5569-member-mgmt.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> My Account APIを使用して、ユーザーが自分のアカウント情報を管理できるようにする方法について説明します。

# My Account API

export const ReleaseStageNotice = ({feature, stage, plans, contact, terms}) => {
  const stageTextMap = {
    "beta": "Beta",
    "ea": "Early Access"
  };
  const stageText = stageTextMap[stage] || "a product release stage";
  const prsLink = "/docs/troubleshoot/product-lifecycle/product-release-stages";
  const linkify = (text, url) => {
    return <a href={url} target="_blank" rel="noreferrer" class="link">{text}</a>;
  };
  const includeDetails = (plans, contact, terms) => {
    const hasDetails = terms || plans || contact;
    if (!hasDetails) return null;
    return <span data-as="p">
            {plans && <>This feature is available for {linkify(`${plans} plans`, "https://auth0.com/pricing")}. </>}
            {contact && "To participate, contact " + contact + ". "}
            {terms && <>By using this feature, you agree to the applicable Free Trial terms in Okta's {linkify("Master Subscription Agreement", "https://www.okta.com/legal")}.</>}
        </span>;
  };
  return <Warning>
            <span data-as="p">
                <strong>The {feature} feature is in {linkify(stageText, prsLink)}.</strong>
            </span>

            {includeDetails(plans, contact, terms)}
        </Warning>;
};

export const AuthCodeGroup = ({children, dropdown}) => {
  const [processedChildren, setProcessedChildren] = useState(children);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      unsubscribe = window.autorun(() => {
        const processChildren = node => {
          if (typeof node === "string") {
            let processedNode = node;
            for (const [key, value] of window.rootStore.variableStore.values.entries()) {
              const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
              processedNode = processedNode.replaceAll(new RegExp(escapedKey, "g"), value);
            }
            return processedNode;
          } else if (Array.isArray(node)) {
            return node.map(processChildren);
          } else if (node && node.props && node.props.children) {
            return {
              ...node,
              props: {
                ...node.props,
                children: processChildren(node.props.children)
              }
            };
          }
          return node;
        };
        setProcessedChildren(processChildren(children));
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  return <CodeGroup dropdown={dropdown}>{processedChildren}</CodeGroup>;
};

Auth0 My Account APIは、ユーザーが自分のアカウント情報を管理するための専用エンドポイントを提供します。これらのAPIを使用して、アプリケーション内にセルフサービス機能を構築したり、ユーザーアカウントに詳細情報を段階的に追加したりできます。

My Account APIは、現在ログインしているユーザーのコンテキスト内で動作し、ユーザー向けアプリケーション内で直接使用できます。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  **Auth0ドメインの使用とカスタムドメインの使用**

  My Account APIは、正規のAuth0ドメインまたはカスタムドメインの使用をサポートしていますが、以下のプロセス全体で同じドメインを使用する必要があります。

  * アクセストークンの取得
  * `audience`値の設定
  * My Account APIエンドポイントの呼び出し

  詳細については、「[カスタムドメイン](/docs/ja-jp/customize/custom-domains)」をご覧ください。
</Callout>

## My Account APIを有効にする

以下のように、<Tooltip tip="Auth0 DashboardでテナントのMy Account APIを有効にできます。サービスを構成するためのAuth0の主製品。" cta="用語集を表示" href="/docs/glossary?term=Auth0+Dashboard">Auth0 Dashboard</Tooltip>：

1. \*\*［アプリケーション］>［API］\*\*に移動します。
2. **MyAccount API**のバナーを見つけます。
3. \*\*［アクティブ化］\*\*を選択します。

<Frame>
  <img src="https://mintcdn.com/docs-staging-feat-docs-5569-member-mgmt/w9QOryXH9ngXdt9p/docs/images/cdy7uua7fh8z/DGkDQNIHcegN8vtQyEvF3/a2e98b06867701a66fa1f1b3df1c996b/My_Account_API_-_Activate.png?fit=max&auto=format&n=w9QOryXH9ngXdt9p&q=85&s=c02c0ed2f31b7d386b486faad272d043" alt="MyAccount APIバナーと［アクティブ化］ボタンが表示されたAuth0 DashboardのAPIページ" width="1139" height="406" data-path="docs/images/cdy7uua7fh8z/DGkDQNIHcegN8vtQyEvF3/a2e98b06867701a66fa1f1b3df1c996b/My_Account_API_-_Activate.png" />
</Frame>

デフォルトでは、Auth0はMy Account APIを作成する際、アプリケーションAPIアクセス ポリシーとして以下を設定します。

* ユーザーフローの場合は`require_client_grant`
* クライアント（マシンツーマシン）フローの場合は`deny_all`

ユーザーに代わってMy Account APIにアクセスするアプリケーションに対しては、明示的にそのアプリケーション用のクライアント付与を作成して、アプリケーションがリクエストできるスコープの最大数を定義できるようにする必要があります。あるいは、ユーザーアクセスフローのポリシーを`allow_all`に変更すると、テナント内のすべてのアプリケーションがMy Account APIに対して任意のスコープをリクエストできるようになります。

My Account APIは機密情報や機密性の高い操作を公開しているため、Auth0ではユーザーアクセスフローに`allow_all`を使用することを推奨していません。My Account APIでは最小特権の原則に従い、アプリケーションが本当に必要なものだけにアクセスできるようにして、潜在的なセキュリティリスクを最小限に抑える必要があります。

Auth0は、アプリケーションAPIアクセスポリシーによって許可されるスコープや、エンドユーザーに割り当てられたRole-based Access Control（RBAC）の権限、ユーザーの同意（該当する場合）を突き合わせることで、アプリケーションに付与する最終的な権限を決定します。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  My Account APIへクライアントがアクセスする際のアプリケーションAPIポリシーは更新できません。つまり、クライアントの資格情報フローを使用してMy Account APIにアクセスすることはできません。
</Callout>

アプリケーションAPIアクセスポリシーとそれに関連するクライアント付与を管理する方法について詳しくは、「[APIへのアプリケーションアクセス：クライアント付与](/docs/ja-jp/get-started/applications/application-access-to-apis-client-grants)」をご覧ください。

## デフォルトポリシー

<ReleaseStageNotice feature="My Account APIの認証保証" stage="ea" terms="true" contact="Auth0 Support" />

デフォルトポリシーでは、[ステップアップ認証](/docs/ja-jp/secure/multi-factor-authentication/step-up-authentication)を必須とすることで、My Account APIに組み込みの認証保証を提供します。有効にすると、Auth0は自動的に、ユーザーが最近認証を行ったことと、2つ目の要素を使用して認証していることを要求します。

このポリシーでは、15分以内での2FAの完了を要求します。Auth0は、ログイン時と、リフレッシュトークン交換のたびにこのルールを適用します。

* ユーザーが登録済みのMFA要素を持っている場合、ログイン時に2FAを完了する必要があります。また、トークンの発行から15分を超えた後にも、再度2FAを完了する必要があります。
* ユーザーに登録可能な要素がない場合、Auth0は初回アクセスを許可しますが、15分経過後のリフレッシュトークン交換時に`unmet_authentication_requirements`エラーを返します。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  デフォルトポリシーはクラシックログインと互換性がありません。テナントでユニバーサルログインまたはサポート対象の埋め込みフロー（[リソース所有者のパスワードフロー](/docs/ja-jp/get-started/authentication-and-authorization-flow/resource-owner-password-flow)または[ネイティブパスキー](/docs/ja-jp/authenticate/database-connections/passkeys/native-passkeys-api)）を使用している場合は、この機能を有効にしてください。
</Callout>

### デフォルトポリシーを有効にする

My Account APIでデフォルトポリシーを有効にするには、次の手順を実行します。

1. [**［アプリケーション］>［API］**](https://manage.auth0.com/#/apis)に移動し、\*\*［My Account API］\*\*を選択します。
2. \*\*［設定］\*\*タブを選択します。
3. \*\*［デフォルトポリシー］**で**［2FAを必須にする］\*\*をオンにします。
4. \*\*［保存］\*\*を選択します。

テナントでデフォルトポリシーを有効にすると、Auth0は新しいMy Account APIを作成するたびに、デフォルトポリシーを自動的に適用します。

### 認証要件の優先順位

デフォルトポリシーは、テナントレベルのMFAポリシーと、Actionsで定義したMFAロジックの間に位置します。

1. **テナントのMFAポリシー**：ベースとなるデフォルトで、テナント内のすべての認証に適用されます。
2. **デフォルトポリシー**：My Account APIに対して、テナントレベルのポリシーを上書きします。
3. **Actions**：ActionsのMFAコマンドは、常に上記2つより優先されます。

### デフォルトポリシーの動作

ユーザーに登録可能な2つ目の認証要素があるかどうかによって動作が異なります。

**MFA要素を登録済みのユーザー**

TOTP、メール、その他のサポート対象の要素を登録しているユーザーの場合、以下のように動作します。

1. ログイン時、Auth0はトークンを発行する前に、登録済みの要素を使用して認証するようユーザーにチャレンジを行います。
2. リフレッシュトークンには、認証方法とタイムスタンプ（AMR）が記録されます。
3. 最後のチャレンジから15分以内にリフレッシュトークンを交換した場合、Auth0は再度チャレンジせずに新しいアクセストークンを発行します。
4. 15分経過後にリフレッシュトークンを交換した場合、Auth0はトークンを発行する前に、再度ユーザーにチャレンジを行います。

**MFA要素を登録していないユーザー**

検証済みのメールアドレスがなく、登録済みの要素もないユーザーの場合、以下のように動作します。

1. ログイン時、Auth0は2つ目の要素なしでアクセスを許可します。
2. 15分以内にリフレッシュトークンを交換した場合、Auth0は再度チャレンジせずに新しいアクセストークンを発行します。
3. 15分経過後にリフレッシュトークンを交換した場合、Auth0は`unmet_authentication_requirements`エラーを返します。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  Auth0がリフレッシュトークンの交換時に`unmet_authentication_requirements`を返した場合、トークンのリフレッシュはできません。アプリケーションは、再度認証フロー全体を開始して、新しいトークンを取得する必要があります。

  サイレントログイン（`prompt=none`）でも、15分経過後にユーザーがポリシーの要件を満たせない場合は、同じエラーが返ります。
</Callout>

## アクセストークン取得する

<Tooltip tip="アクセストークン：APIへのアクセスに使用する、非透過的な文字列またはJWT形式の認証資格情報。" cta="用語集を表示" href="/docs/glossary?term=access+token">自分で作成したAPIのアクセストークン</Tooltip>を取得するのと同じ方法で、My Account APIのアクセストークンを取得できます。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  デフォルトポリシーよりも高度な認証保証が必要な場合（たとえば、特定の要素を必須にしたり、特定の操作にのみ要件を適用したりする場合）は、[Actions](/docs/ja-jp/customize/actions)を使用した[ステップアップ認証](/docs/ja-jp/secure/multi-factor-authentication/step-up-authentication)によって、カスタムMFAロジックを定義できます。Actionsは常にデフォルトポリシーより優先されることに注意してください。
</Callout>

<Tooltip tip="ユニバーサルログイン：アプリケーションは、Auth0の認可サーバーにホストされたユニバーサルログインにリダイレクトすることで、ユーザーのアイデンティティを検証します。" cta="用語集を表示" href="/docs/glossary?term=Universal+Login">ユニバーサルログイン</Tooltip>を使用している場合、以下の記事を参照してください。

* [認可コードフローを使用してAPIを呼び出す](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow)
* [PKCEを使った認可コードフローでAPIを呼び出す](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce)

埋め込みログインを使用する場合には、次の記事を参照してください。

* [リソース所有者のパスワードフローを使ってAPIを呼び出す](/docs/ja-jp/get-started/authentication-and-authorization-flow/resource-owner-password-flow/call-your-api-using-resource-owner-password-flow)
* [ネイティブPasskeys APIを使用したログインフロー](/docs/ja-jp/authenticate/database-connections/passkeys/native-passkeys-api#login-flow)

### オーディエンス

<Tooltip tip="オーディエンス：発行されたトークンのオーディエンスの一意の識別子。トークン内ではaudと呼ばれ、その値には、IDトークンではアプリケーション（クライアントID）またはアクセストークンではAPI（API識別子）のいずれかのIDが含まれています。" cta="用語集を表示" href="/docs/glossary?term=audience">My Account APIのオーディエンス</Tooltip>は`https://{yourDomain}/me/`です。

### スコープ

My Account APIは次のスコープをサポートしています。

| スコープ                               | 説明                        |
| ---------------------------------- | ------------------------- |
| `create:me:authentication_methods` | ユーザーが新しい認証方法を登録できるようにします。 |
| `read:me:authentication_methods`   | ユーザーが既存の認証方法を確認できるようにします。 |
| `update:me:authentication_methods` | ユーザーが既存の認証方法を変更できるようにします。 |
| `delete:me:authentication_methods` | ユーザーが既存の認証方法を削除できるようにします。 |
| `read:me:factors`                  | ユーザーが登録可能な要素を確認できるようにします  |

[トークンボールトを使用した接続済みアカウント](/docs/ja-jp/secure/call-apis-on-users-behalf/token-vault/connected-accounts-for-token-vault)では、My Account APIで以下のスコープがサポートされています。

| スコープ                           | 説明                                            |
| ------------------------------ | --------------------------------------------- |
| `create:me:connected_accounts` | ユーザーが新しいアカウントをユーザープロファイルに接続できるようにします。         |
| `read:me:connected_accounts`   | ユーザーがユーザープロファイルにリンクされている既存のアカウントを確認できるようにします。 |
| `delete:me:connected_accounts` | ユーザーがユーザープロファイルから接続済みアカウントを削除できるようにします。       |

### アクセストークンの例

#### 認可コードフローを使用したユニバーサルログイン

[Auth0のユニバーサルログイン](/docs/ja-jp/authenticate/login/auth0-universal-login#auth0-universal-login)でアクセストークンを取得するには、2つのステップがあります。まず認可コードをリクエストし、次にそのコードをアクセストークンと交換します。この付与タイプについて詳しくは、「[認可コードフロー](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow)」をご覧ください。

まず、`/authorize`エンドポイントにAPI呼び出しを送信して、認可コードをリクエストします。

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request GET \
    --url 'https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F");
  var request = new RestRequest(Method.GET);
  IRestResponse response = client.Execute(request);
  ```

  ```go Go theme={null}
  package main

  import (
      "fmt"
      "net/http"
      "io/ioutil"
  )

  func main() {

      url := "https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F"

      req, _ := http.NewRequest("GET", url, nil)

      res, _ := http.DefaultClient.Do(req)

      defer res.Body.Close()
      body, _ := ioutil.ReadAll(res.Body)

      fmt.Println(res)
      fmt.Println(string(body))

  }
  ```

  ```java Java theme={null}
  HttpResponse<String> response = Unirest.get("https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F")
    .asString();
  ```

  ```javascript Node.js theme={null}
  var axios = require("axios").default;

  var options = {
    method: 'GET',
    url: 'https://{yourDomain}/authorize',
    params: {
      response_type: 'code',
      client_id: '{yourClientId}',
      redirect_uri: '{yourRedirectUri}',
      scope: 'create:me:authentication_methods',
      offline_access: '',
      audience: 'https://{yourDomain}/me/'
    }
  };

  axios.request(options).then(function (response) {
    console.log(response.data);
  }).catch(function (error) {
    console.error(error);
  });
  ```

  ```php PHP theme={null}
  $curl = curl_init();

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
  ]);

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    echo $response;
  }
  ```

  ```python Python theme={null}
  import http.client

  conn = http.client.HTTPSConnection("")

  conn.request("GET", "/{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F")

  res = conn.getresponse()
  data = res.read()

  print(data.decode("utf-8"))
  ```

  ```ruby Ruby theme={null}
  require 'uri'
  require 'net/http'
  require 'openssl'

  url = URI("https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER

  request = Net::HTTP::Get.new(url)

  response = http.request(request)
  puts response.read_body
  ```
</AuthCodeGroup>

次に、コードをアクセストークンと交換します。

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request POST \
    --url 'https://{yourDomain}/oauth/token' \
    --header 'content-type: application/json' \
    --data '{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientSecret}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "https://{yourDomain}/me/","scope": "create:me:authentication_methods","offline_access": ""}'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/oauth/token");
  var request = new RestRequest(Method.POST);
  request.AddHeader("content-type", "application/json");
  request.AddParameter("application/json", "{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientSecret}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "https://{yourDomain}/me/","scope": "create:me:authentication_methods","offline_access": ""}", ParameterType.RequestBody);
  IRestResponse response = client.Execute(request);
  ```

  ```go Go theme={null}
  package main

  import (
      "fmt"
      "strings"
      "net/http"
      "io/ioutil"
  )

  func main() {

      url := "https://{yourDomain}/oauth/token"

      payload := strings.NewReader("{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientSecret}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "https://{yourDomain}/me/","scope": "create:me:authentication_methods","offline_access": ""}")

      req, _ := http.NewRequest("POST", url, payload)

      req.Header.Add("content-type", "application/json")

      res, _ := http.DefaultClient.Do(req)

      defer res.Body.Close()
      body, _ := ioutil.ReadAll(res.Body)

      fmt.Println(res)
      fmt.Println(string(body))

  }
  ```

  ```java Java theme={null}
  HttpResponse<String> response = Unirest.post("https://{yourDomain}/oauth/token")
    .header("content-type", "application/json")
    .body("{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientSecret}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "https://{yourDomain}/me/","scope": "create:me:authentication_methods","offline_access": ""}")
    .asString();
  ```

  ```javascript Node.js theme={null}
  var axios = require("axios").default;

  var options = {
    method: 'POST',
    url: 'https://{yourDomain}/oauth/token',
    headers: {'content-type': 'application/json'},
    data: {
      grant_type: 'authorization_code',
      client_id: '{yourClientId}',
      client_secret: '{yourClientSecret}',
      code: '{yourAuthorizationCode}',
      redirect_uri: '{yourRedirectUri}',
      audience: 'https://{yourDomain}/me/',
      scope: 'create:me:authentication_methods',
      offline_access: ''
    }
  };

  axios.request(options).then(function (response) {
    console.log(response.data);
  }).catch(function (error) {
    console.error(error);
  });
  ```

  ```php PHP theme={null}
  $curl = curl_init();

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://{yourDomain}/oauth/token",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientSecret}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "https://{yourDomain}/me/","scope": "create:me:authentication_methods","offline_access": ""}",
    CURLOPT_HTTPHEADER => [
      "content-type: application/json"
    ],
  ]);

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    echo $response;
  }
  ```

  ```python Python theme={null}
  import http.client

  conn = http.client.HTTPSConnection("")

  payload = "{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientSecret}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "https://{yourDomain}/me/","scope": "create:me:authentication_methods","offline_access": ""}"

  headers = { 'content-type': "application/json" }

  conn.request("POST", "/{yourDomain}/oauth/token", payload, headers)

  res = conn.getresponse()
  data = res.read()

  print(data.decode("utf-8"))
  ```

  ```ruby Ruby theme={null}
  require 'uri'
  require 'net/http'
  require 'openssl'

  url = URI("https://{yourDomain}/oauth/token")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER

  request = Net::HTTP::Post.new(url)
  request["content-type"] = 'application/json'
  request.body = "{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientSecret}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "https://{yourDomain}/me/","scope": "create:me:authentication_methods","offline_access": ""}"

  response = http.request(request)
  puts response.read_body
  ```
</AuthCodeGroup>

#### ネイティブパスキーを使用した埋め込みログイン

[パスキー](/docs/ja-jp/authenticate/database-connections/passkeys)を埋め込みアプリケーションのログインフローに含めるには、まずログインチャレンジをリクエストします。

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request POST \
    --url 'https://{yourDomain}/passkey/challenge' \
    --header 'content-type: application/json' \
    --data '{"client_id": "{yourClientId}"}'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/passkey/challenge");
  var request = new RestRequest(Method.POST);
  request.AddHeader("content-type", "application/json");
  request.AddParameter("application/json", "{"client_id": "{yourClientId}"}", ParameterType.RequestBody);
  IRestResponse response = client.Execute(request);
  ```

  ```go Go theme={null}
  package main

  import (
      "fmt"
      "strings"
      "net/http"
      "io/ioutil"
  )

  func main() {

      url := "https://{yourDomain}/passkey/challenge"

      payload := strings.NewReader("{"client_id": "{yourClientId}"}")

      req, _ := http.NewRequest("POST", url, payload)

      req.Header.Add("content-type", "application/json")

      res, _ := http.DefaultClient.Do(req)

      defer res.Body.Close()
      body, _ := ioutil.ReadAll(res.Body)

      fmt.Println(res)
      fmt.Println(string(body))

  }
  ```

  ```java Java theme={null}
  HttpResponse<String> response = Unirest.post("https://{yourDomain}/passkey/challenge")
    .header("content-type", "application/json")
    .body("{"client_id": "{yourClientId}"}")
    .asString();
  ```

  ```javascript Node.js theme={null}
  var axios = require("axios").default;

  var options = {
    method: 'POST',
    url: 'https://{yourDomain}/passkey/challenge',
    headers: {'content-type': 'application/json'},
    data: {client_id: '{yourClientId}'}
  };

  axios.request(options).then(function (response) {
    console.log(response.data);
  }).catch(function (error) {
    console.error(error);
  });
  ```

  ```php PHP theme={null}
  $curl = curl_init();

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://{yourDomain}/passkey/challenge",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "{"client_id": "{yourClientId}"}",
    CURLOPT_HTTPHEADER => [
      "content-type: application/json"
    ],
  ]);

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    echo $response;
  }
  ```

  ```python Python theme={null}
  import http.client

  conn = http.client.HTTPSConnection("")

  payload = "{"client_id": "{yourClientId}"}"

  headers = { 'content-type': "application/json" }

  conn.request("POST", "/{yourDomain}/passkey/challenge", payload, headers)

  res = conn.getresponse()
  data = res.read()

  print(data.decode("utf-8"))
  ```

  ```ruby Ruby theme={null}
  require 'uri'
  require 'net/http'
  require 'openssl'

  url = URI("https://{yourDomain}/passkey/challenge")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER

  request = Net::HTTP::Post.new(url)
  request["content-type"] = 'application/json'
  request.body = "{"client_id": "{yourClientId}"}"

  response = http.request(request)
  puts response.read_body
  ```
</AuthCodeGroup>

次に、既存のユーザーを認証します。

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request POST \
    --url 'https://{yourDomain}/oauth/token' \
    --header 'content-type: application/json' \
    --data '{  "grant_type": "urn:okta:params:oauth:grant-type:webauthn",  "client_id": "{yourClientId}",  "scope": "create:me:authentication_methods offline_access",  "audience": "https://{yourDomain}/me/",  "auth_session": "{sessionIdFromTheFirstRequest}",  "authn_response": "{authenticatorResponse}"}'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/oauth/token");
  var request = new RestRequest(Method.POST);
  request.AddHeader("content-type", "application/json");
  request.AddParameter("application/json", "{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}", ParameterType.RequestBody);
  IRestResponse response = client.Execute(request);
  ```

  ```go Go theme={null}
  package main

  import (
      "fmt"
      "strings"
      "net/http"
      "io/ioutil"
  )

  func main() {

      url := "https://{yourDomain}/oauth/token"

      payload := strings.NewReader("{  "grant_type": "urn:okta:params:oauth:grant-type:webauthn",  "client_id": "{yourClientId}",  "scope": "create:me:authentication_methods offline_access",  "audience": "https://{yourDomain}/me/",  "auth_session": "{sessionIdFromTheFirstRequest}",  "authn_response": "{authenticatorResponse}"}")

      req, _ := http.NewRequest("POST", url, payload)

      req.Header.Add("content-type", "application/json")

      res, _ := http.DefaultClient.Do(req)

      defer res.Body.Close()
      body, _ := ioutil.ReadAll(res.Body)

      fmt.Println(res)
      fmt.Println(string(body))

  }
  ```

  ```java Java theme={null}
  HttpResponse<String> response = Unirest.post("https://{yourDomain}/oauth/token")
    .header("content-type", "application/json")
    .body("{  "grant_type": "urn:okta:params:oauth:grant-type:webauthn",  "client_id": "{yourClientId}",  "scope": "create:me:authentication_methods offline_access",  "audience": "https://{yourDomain}/me/",  "auth_session": "{sessionIdFromTheFirstRequest}",  "authn_response": "{authenticatorResponse}"}")
    .asString();
  ```

  ```javascript Node.js theme={null}
  var axios = require("axios").default;

  var options = {
    method: 'POST',
    url: 'https://{yourDomain}/oauth/token',
    headers: {'content-type': 'application/json'},
    data: '{  "grant_type": "urn:okta:params:oauth:grant-type:webauthn",  "client_id": "{yourClientId}",  "scope": "create:me:authentication_methods offline_access",  "audience": "https://{yourDomain}/me/",  "auth_session": "{sessionIdFromTheFirstRequest}",  "authn_response": "{authenticatorResponse}"}'
  };

  axios.request(options).then(function (response) {
    console.log(response.data);
  }).catch(function (error) {
    console.error(error);
  });
  ```

  ```php PHP theme={null}
  $curl = curl_init();

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://{yourDomain}/oauth/token",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "{  "grant_type": "urn:okta:params:oauth:grant-type:webauthn",  "client_id": "{yourClientId}",  "scope": "create:me:authentication_methods offline_access",  "audience": "https://{yourDomain}/me/",  "auth_session": "{sessionIdFromTheFirstRequest}",  "authn_response": "{authenticatorResponse}"}",
    CURLOPT_HTTPHEADER => [
      "content-type: application/json"
    ],
  ]);

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    echo $response;
  }
  ```

  ```python Python theme={null}
  import http.client

  conn = http.client.HTTPSConnection("")

  payload = "{  "grant_type": "urn:okta:params:oauth:grant-type:webauthn",  "client_id": "{yourClientId}",  "scope": "create:me:authentication_methods offline_access",  "audience": "https://{yourDomain}/me/",  "auth_session": "{sessionIdFromTheFirstRequest}",  "authn_response": "{authenticatorResponse}"}"

  headers = { 'content-type': "application/json" }

  conn.request("POST", "/{yourDomain}/oauth/token", payload, headers)

  res = conn.getresponse()
  data = res.read()

  print(data.decode("utf-8"))
  ```

  ```ruby Ruby theme={null}
  require 'uri'
  require 'net/http'
  require 'openssl'

  url = URI("https://{yourDomain}/oauth/token")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER

  request = Net::HTTP::Post.new(url)
  request["content-type"] = 'application/json'
  request.body = "{  "grant_type": "urn:okta:params:oauth:grant-type:webauthn",  "client_id": "{yourClientId}",  "scope": "create:me:authentication_methods offline_access",  "audience": "https://{yourDomain}/me/",  "auth_session": "{sessionIdFromTheFirstRequest}",  "authn_response": "{authenticatorResponse}"}"

  response = http.request(request)
  puts response.read_body
  ```
</AuthCodeGroup>

## 認証方法を管理する

My Account APIを使用すると、エンドユーザーが自分の認証方法を登録・管理できるように、認証方法を設定できます。ほとんどの認証方法では、2段階のフローを使用します。まず登録を開始し、次に登録を確認します。

サポートされている認証方法については、以下の表をご覧ください。

| タイプ                                 | 登録動作                                                                                                                                                                                                                                                                                                                                                                                  | APIで登録可能     |
| :---------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :----------- |
| `email`<br />セカンダリ（MFA）             | `POST { "type": "email" }` `email`を`POST`リクエストに含めます。Auth0はそのアドレスにワンタイムコードを送信します。検証リクエストでは、そのコードを`otp_code`として送信します。                                                                                                                                                                                                                                                                   | はい           |
| `phone`<br />セカンダリ（MFA）             | `POST { "type": "sms" }` Auth0は電話番号にワンタイムコードを送信します。検証リクエストでは、そのコードを`otp_code`として送信します。                                                                                                                                                                                                                                                                                                | はい           |
| `totp`<br />セカンダリ（MFA）              | `POST { "type": "totp" }` レスポンスには以下が含まれます。<ul><li>`barcode_uri`：ユーザーが認証アプリでスキャンできるQRコードとして表示されます。</li><li>`manual_input_code`：QRコードをスキャンできないユーザー向けのTOTPシークレットです。</li></ul>                                                                                                                                                                                                            | はい           |
| `push-notification`<br />セカンダリ（MFA） | `POST { "type": "push-notification" }` レスポンスには、ユーザーがスキャンして認証アプリをリンクするための`barcode_uri`が含まれます。検証リクエストでは`auth_session`のみが必要で、`otp_code`は必要ありません。ユーザーがアプリでプッシュ通知を承認すると、Auth0が登録を完了します。                                                                                                                                                                                                    | はい           |
| `recovery-code`<br />セカンダリ（MFA）     | `POST { "type": "recovery-code" }` レスポンスには`recovery_code`が含まれます。この値は再取得できないため、直ちにユーザーに表示してください。検証リクエストでは`auth_session`のみが必要です。                                                                                                                                                                                                                                                        | はい           |
| `password`<br />プライマリ               | `POST { "type": "password" }` レスポンスには、テナントのパスワード要件（最小文字数、使用可能な文字種、履歴、辞書設定など）を記述した`policy`オブジェクトが含まれます。検証リクエストでは、`auth_session`とともに`new_password`を送信します。Auth0は登録を確認する前に、パスワードがポリシーを満たしているかを検証します。                                                                                                                                                                                      | はい           |
| `passkey`<br />プライマリ                | `POST { "type": "passkey" }`。レスポンスにはIDは含まれません。代わりに、以下を返します。<ul><li>`auth_session`：`POST /authentication-methods`で返される、登録用の一意のセッション識別子です。</li><li>`authn_params_public_key`：WebAuthnの`PublicKeyCredentialCreationOptions`を`navigator.credentials.create()`に渡せるようにします。検証リクエストでは、完全なWebAuthnの`AuthenticatorAttestationResponse`を`authn_response`として送信します。検証レスポンスでメソッドIDが返されます。</li></ul> | はい           |
| `webauthn-platform`<br />セカンダリ（MFA） | 現在、登録はサポートされていません。                                                                                                                                                                                                                                                                                                                                                                    | いいえ — 読み取り専用 |
| `webauthn-roaming`<br />セカンダリ（MFA）  | 現在、登録はサポートされていません。                                                                                                                                                                                                                                                                                                                                                                    | いいえ — 読み取り専用 |

### 登録フロー

認証方法の登録は、2段階のプロセスで行います。

1. 登録を開始するには、メソッドのタイプと必要なフィールドを指定して、`/me/authentication-methods`に対して`POST`を送信します。Auth0は、`auth_session`トークンと、メソッドのタイプに応じた登録情報を返します。
2. 登録を確認するには、`auth_session`と、そのメソッドのタイプに応じた検証資格情報（OTPコード、新しいパスワード、またはWebAuthnレスポンス）を指定して、`/me/authentication-methods/{id}/verify`に対して`POST`を送信します。

登録が確認されると、その後の`GET`レスポンスで、Auth0はそのメソッドの`confirmed`フィールドに`true`を設定します。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  パスキーの登録では、`POST`レスポンスにIDは含まれません。Auth0は、検証ステップが成功した後にのみIDを返します。
</Callout>

### 認証方法の管理の例

#### TOTP Authenticatorを登録する

TOTPの登録は、TOTP登録の開始とTOTP登録の確認という2段階のプロセスで行います。

まず登録を開始し、ユーザーがAuthenticatorアプリに追加するためのQRコードと手動入力用のシークレットを取得します。

<Tabs>
  <Tab title="要求">
    ```bash theme={null}
    curl --request POST \
      --url 'https://{yourDomain}/me/v1/authentication-methods' \
      --header 'Authorization: Bearer {yourAccessToken}' \
      --header 'Content-Type: application/json' \
      --data '{"type": "totp"}'
    ```
  </Tab>

  <Tab title="応答">
    ```json theme={null}
    {
      "id": "amr_abc123",
      "auth_session": "eyJhbGci...",
      "barcode_uri": "otpauth://totp/YourApp:user%40example.com?secret=JBSWY3DPEHPK3PXP&issuer=YourApp",
      "manual_input_code": "JBSWY3DPEHPK3PXP"
    }
    ```
  </Tab>
</Tabs>

次に、ユーザーのAuthenticatorアプリから取得したワンタイムコードを、前のレスポンスで返された`auth_session`と`id`とともに送信して、登録を確認します。

<Tabs>
  <Tab title="要求">
    ```bash theme={null}
    curl --request POST \
      --url 'https://{yourDomain}/me/v1/authentication-methods/{id}/verify' \
      --header 'Authorization: Bearer {yourAccessToken}' \
      --header 'Content-Type: application/json' \
      --data '{"auth_session": "{yourAuthSession}", "otp_code": "{yourOtpCode}"}'
    ```
  </Tab>

  <Tab title="応答">
    ```json theme={null}
    {
      "id": "amr_abc123",
      "type": "totp",
      "confirmed": true,
      "created_at": "2024-01-15T10:30:00.000Z",
      "updated_at": "2024-01-15T10:35:00.000Z"
    }
    ```
  </Tab>
</Tabs>

#### 認証方法の一覧を取得する

現在のユーザーが登録しているすべての認証方法を取得します。`confirmed`フィールドは、登録が完了しているかどうかを示します。

<Tabs>
  <Tab title="要求">
    ```bash theme={null}
    curl --request GET \
      --url 'https://{yourDomain}/me/v1/authentication-methods' \
      --header 'Authorization: Bearer {yourAccessToken}'
    ```
  </Tab>

  <Tab title="応答">
    ```json theme={null}
    [
      {
        "id": "amr_abc123",
        "type": "totp",
        "confirmed": true,
        "created_at": "2024-01-15T10:30:00.000Z",
        "updated_at": "2024-01-15T10:35:00.000Z"
      },
      {
        "id": "amr_def456",
        "type": "email",
        "email": "user@example.com",
        "confirmed": true,
        "created_at": "2024-01-10T08:00:00.000Z",
        "updated_at": "2024-01-10T08:05:00.000Z"
      }
    ]
    ```
  </Tab>
</Tabs>

#### 認証方法を削除する

登録済みの認証方法を削除します。`{id}`を、一覧取得のレスポンスで返されたその認証方法の`id`に置き換えます。

<Tabs>
  <Tab title="要求">
    ```bash theme={null}
    curl --request DELETE \
      --url 'https://{yourDomain}/me/v1/authentication-methods/{id}' \
      --header 'Authorization: Bearer {yourAccessToken}'
    ```
  </Tab>

  <Tab title="応答">
    ```text theme={null}
    HTTP 204 No Content
    ```
  </Tab>
</Tabs>

## Cross-Originリクエスト

Auth0テナントとは異なるドメインで実行されているブラウザーベースのアプリケーション（シングルページアプリケーションなど）からMy Account APIを直接呼び出す場合、[Cross-Origin Resource Sharing（CORS）](/docs/ja-jp/authenticate/passwordless/implement-login/embedded-login/spa#configure-cross-origin-resource-sharing-cors)と呼ばれるブラウザーのセキュリティポリシーが適用されます。デフォルトでは、ブラウザーはこのようなcross-originリクエストをブロックします。

アプリケーションがAPIに正常にリクエストできるようにするには、次の手順で、アプリケーションのドメイン（その「オリジン」）をクライアントの構成に追加する必要があります。

1. [［ダッシュボード］>［アプリケーション］](https://manage.auth0.com/#/applications)に移動します。［アプリケーション］ビューを選択します。
2. \*\*［Cross-Origin認証］**で、**［Cross-Origin認証を許可する］\*\*をオンにします。
3. \*\*［許可されたオリジン（CORS）］\*\*を見つけて、アプリケーションのオリジンURLを入力します。
4. \*\*［保存］\*\*を選択します。

詳しくは、「[Cross-Originリソース共有を構成する](/docs/ja-jp/get-started/applications/set-up-cors)」をご覧ください。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  アプリケーションにCORSを使う必要がない場合は、\*\*［Cross-origin認証を許可する］\*\*が無効であることを確認してください。このリストにアプリケーションのURLを追加すると、Auth0はそのオリジンからのリクエストを信頼するようになり、クライアント側のアプリケーションからAPIにアクセスできるようになります。
</Callout>
