> ## Documentation Index
> Fetch the complete documentation index at: https://translations.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": "早期アクセス"
  };
  const stageText = stageTextMap[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 && <>この機能は{linkify(`${plans}プラン`, "https://auth0.com/pricing")}でご利用いただけます。 </>}
            {contact && "参加をご希望の場合は、" + contact + "までお問い合わせください。 "}
            {terms && <>この機能を使用することにより、Oktaの該当する無料トライアル規約および{linkify("Master Subscription Agreement", "https://www.okta.com/legal")}に同意したものとみなされます。</>}
        </span>;
  };
  return <Warning>
            <span data-as="p">
                <strong>{feature}機能は現在、{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 エンドポイントを呼び出す

  詳細については、[Custom Domains](/docs/ja-jp/customize/custom-domains) をご覧ください。
</Callout>

<div id="activate-the-my-account-api">
  ## My Account API を有効化する
</div>

<Tooltip tip="Auth0 Dashboard: サービスを設定するための Auth0 の主要製品です。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Auth0+Dashboard">Auth0 Dashboard</Tooltip> で、テナントの My Account API を有効化できます。

1. **Applications > APIs** に移動します。
2. **MyAccount API** バナーを見つけます。
3. **有効化** を選択します。

<Frame>
  <img src="https://mintcdn.com/translations/mMSz-RNYLuOm2GmQ/docs/images/cdy7uua7fh8z/DGkDQNIHcegN8vtQyEvF3/a2e98b06867701a66fa1f1b3df1c996b/My_Account_API_-_Activate.png?fit=max&auto=format&n=mMSz-RNYLuOm2GmQ&q=85&s=112e02761463f84deb6f416f04c11171" alt="MyAccount API バナーと有効化ボタンが表示された Auth0 Dashboard の APIs ページ" 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`
* クライアント (machine-to-machine) フローには `deny_all`

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

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

Auth0 は、アプリケーション API アクセスポリシーで許可されたスコープ、エンドユーザーに割り当てられたロールベースのアクセス制御 (RBAC) の permissions、およびユーザーの同意 (該当する場合) の積集合によって、アプリケーションに最終的に付与される permissions を決定します。

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

アプリケーション API アクセスポリシーとそれに関連付けられたクライアントグラントの管理方法の詳細については、[Application Access to APIs: Client Grants](/docs/ja-jp/get-started/applications/application-access-to-apis-client-grants) を参照してください。

<div id="default-policy">
  ## デフォルトポリシー
</div>

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

デフォルトポリシー は、[Step-up Authentication](/docs/ja-jp/secure/multi-factor-authentication/step-up-authentication) を必須にすることで、My Account API に組み込みの認証保証を提供します。有効にすると、Auth0 はユーザーが直近で認証されており、かつ第 2 認証要素を使用していることを自動的に適用します。

このポリシーでは、15 分以内の 2FA が必須になります。Auth0 はこのルールをログイン時と、すべてのリフレッシュトークン交換時に適用します。

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

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

<div id="enable-default-policy">
  ### デフォルトポリシーを有効にする
</div>

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

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

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

<div id="authentication-requirements-hierarchy">
  ### 認証要件の階層
</div>

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

1. **テナント MFA ポリシー**: テナント内のすべての認証に適用される基本のデフォルト設定
2. **デフォルトポリシー**: My Account API に限り、テナントレベルの設定を上書きします
3. **Actions**: Actions 内の MFA コマンドは、常にこの両方より優先されます

<div id="default-policy-behavior">
  ### デフォルトポリシーの動作
</div>

この動作は、ユーザーが登録可能な第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` を返した場合、トークンを更新できません。新しいトークンを取得するには、アプリケーションで認証フロー全体を最初からやり直す必要があります。

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

<div id="get-an-access-token">
  ## access token を取得する
</div>

My Account API の<Tooltip tip="Access Token: API へのアクセスに使用する認可資格情報で、不透明な文字列または JWT の形式を取ります。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=access+token">access token</Tooltip>は、独自の API 向けの access token を取得する場合と同じ方法で取得できます。

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

<Tooltip tip="Universal Login: アプリケーションは、ユーザーの本人確認のために、Auth0 の認可サーバーでホストされる Universal Login にリダイレクトされます。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Universal+Login">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 を使用した Authorization Code フローを使用して 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)

組み込みログインを使用している場合は、以下の記事を参照してください。

* [Resource Owner Password Flow を使用して API を呼び出す](/docs/ja-jp/get-started/authentication-and-authorization-flow/resource-owner-password-flow/call-your-api-using-resource-owner-password-flow)
* [Native Passkeys API を使用したログインフロー](/docs/ja-jp/authenticate/database-connections/passkeys/native-passkeys-api#login-flow)

<div id="audience">
  ### Audience
</div>

My Account API の <Tooltip tip="Audience: 発行されたトークンの audience を一意に識別する値です。トークン内では aud と呼ばれ、その値には、ID トークンの場合はアプリケーション（Client ID）の ID、Access Token の場合は API（API 識別子）の ID が含まれます。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=audience">audience</Tooltip> は `https://{yourDomain}/me/` です。

<div id="scope">
  ### スコープ
</div>

My Account API では、次のスコープがサポートされています。

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

[Connected Accounts with Token Vault](/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` | ユーザーが自身のユーザープロファイルから接続済みアカウントを削除できるようにします。         |

<div id="access-token-examples">
  ### アクセストークンの例
</div>

<div id="universal-login-with-authorization-code-flow">
  #### 認可コードフローでのUniversal Login
</div>

[Auth0's Universal Login](/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>

<div id="embedded-login-with-native-passkeys">
  #### Native パスキーを使用する埋め込みログイン
</div>

埋め込みアプリケーションのログインフローに[パスキー](/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>

<div id="manage-authentication-methods">
  ## 認証方法を管理する
</div>

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

サポート対象の認証方法については、次の表を確認してください。

| 種類                                   | 登録時の動作                                                                                                                                                                                                                                                                                                                                                                                                    | API 経由で登録可能  |
| :----------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------- |
| `email`<br />セカンダリ (MFA)             | `POST { "type": "email" }` `POST` リクエストに `email` を含めます。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)  | 現在、登録はサポートされていません。                                                                                                                                                                                                                                                                                                                                                                                        | いいえ — 読み取り専用 |

<div id="enrollment-flow">
  ### 登録フロー
</div>

認証方法の登録は、次の 2 段階で行います。

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

確認が完了すると、Auth0 は以降の `GET` レスポンスで、メソッドの `confirmed` フィールドを `true` に設定します。

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

<div id="manage-authentication-method-examples">
  ### 認証方法の管理例
</div>

<div id="enroll-a-totp-authenticator">
  #### TOTP 認証器を登録する
</div>

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

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

<Tabs>
  <Tab title="リクエスト">
    ```bash theme={null}
    curl --request POST \
      --url 'https://{yourDomain}/me/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>

次に、前のレスポンスの `auth_session` と `id` に、ユーザーの認証器アプリで生成されたワンタイムコードを添えて送信し、登録を確認します。

<Tabs>
  <Tab title="リクエスト">
    ```bash theme={null}
    curl --request POST \
      --url 'https://{yourDomain}/me/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>

<div id="list-authentication-methods">
  #### 認証方法を一覧表示
</div>

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

<Tabs>
  <Tab title="リクエスト">
    ```bash theme={null}
    curl --request GET \
      --url 'https://{yourDomain}/me/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>

<div id="delete-an-authentication-method">
  #### 認証方法をDelete
</div>

登録済みの認証方法を削除します。`{id}` は、一覧レスポンスに含まれる対象の認証方法の `id` に置き換えます。

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

  <Tab title="レスポンス">
    ```text theme={null}
    HTTP 204 No Content
    ```
  </Tab>
</Tabs>

<div id="cross-origin-requests">
  ## クロスオリジン リクエスト
</div>

Auth0 テナントとは異なるドメインで実行されるブラウザベースのアプリケーション (Single Page Application など) から My Account API を直接呼び出す場合、[クロスオリジン リソース共有 (CORS)](/docs/ja-jp/authenticate/passwordless/implement-login/embedded-login/spa#configure-cross-origin-resource-sharing-cors) と呼ばれるブラウザのセキュリティポリシーにより制限を受ける可能性があります。ブラウザはデフォルトで、こうしたクロスオリジン リクエストをブロックします。

アプリケーションから API に正常にリクエストを送信できるようにするには、アプリケーションのドメイン (「origin」) をクライアントの設定に追加する必要があります。

1. [Auth0 Dashboard > アプリケーション](https://manage.auth0.com/#/applications) に移動し、表示するアプリケーションを選択します。
2. **Cross-Origin Authentication** で、**Allow Cross-Origin Authentication** をオンにします。
3. **Allowed Origins (CORS)** を見つけて、アプリケーションの origin URL を入力します。
4. **保存** を選択します。

詳しくは、[Configure Cross-Origin Resource Sharing](/docs/ja-jp/get-started/applications/set-up-cors) を参照してください。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  アプリケーションで CORS を使用する必要がない場合は、**Allow Cross-Origin Authentication** がオフになっていることを確認してください。アプリケーションの URL をこのリストに追加すると、Auth0 はその origin からのリクエストを信頼し、クライアントサイドのアプリケーションから API へアクセスできるようになります。
</Callout>
