> ## 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.

> Form Post を使用した Implicit Flow で、シングルページアプリケーション（SPA）にログインを追加する方法を学びます。

# Form Post を使用した Implicit Flow でログインを追加する

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>;
};

Form Post を使用する Implicit Flow を使って、シングルページアプリケーション (SPA) にログインを追加できます。このフローの仕組みと、これを使用すべき理由については、[Implicit Flow with Form Post](/docs/ja-jp/get-started/authentication-and-authorization-flow/implicit-flow-with-form-post) をお読みください。

Form Post を使用する Implicit Flow は、ログインのみのユースケースで使用してください。ユーザーのログイン時に API を呼び出せるよう <Tooltip tip="アクセストークン: API へのアクセスに使用する認可資格情報で、不透明な文字列または JWT の形式です。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=access+tokens">アクセストークン</Tooltip> もリクエストする必要がある場合は、PKCE を使用した Authorization Code フローを使用してください。詳しくは、[Authorization Code Flow with Proof Key for Code Exchange (PKCE](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce)) をお読みください。

Form Post を使用する Implicit Flow を実装するには、次のリソースを利用できます。

* [Express OpenID Connect SDK](https://www.npmjs.com/package/express-openid-connect): このフローを実装する最も簡単な方法で、面倒な処理の大半を担ってくれます。弊社の Javascript SDK を使用する場合は、ご利用のアーキテクチャに適した対策を実装していることを確認してください。詳しくは、[Auth0.js Reference](/docs/ja-jp/libraries/auth0js) をお読みください。
* [Authentication API](https://auth0.com/docs/api/authentication): 独自のソリューションを構築したい場合は、このまま読み進めて、API を直接呼び出す方法をご確認ください。

ログインが成功すると、アプリケーションはユーザーの [ID トークン](/docs/ja-jp/secure/tokens/id-tokens) にアクセスできるようになります。<Tooltip tip="ID トークン: リソースへのアクセスではなく、クライアント自体のための資格情報です。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=ID+token">ID トークン</Tooltip> には、基本的なユーザープロファイル情報が含まれます。

<div id="prerequisites">
  ## 前提条件
</div>

Auth0 にアプリを登録します。詳しくは、[シングルページアプリケーションの登録](/docs/ja-jp/get-started/auth0-overview/create-applications/single-page-web-apps)を参照してください。

* **アプリケーションの種類**で **Single-Page App** を選択します。
* **Allowed Callback URL** に `{https://yourApp/callback}` を追加します。
* アプリケーションの **グラントタイプ** に **Implicit** が含まれていることを確認します。詳しくは、[グラントタイプの更新](/docs/ja-jp/get-started/applications/update-grant-types)を参照してください。

<div id="authorize-user">
  ## ユーザーを認可する
</div>

ユーザーの認可を取得し、アプリにリダイレクトして戻します。フローを開始するには、まずユーザーの認可を取得する必要があります。このステップには、次のプロセスの 1 つ以上が含まれる場合があります。

* ユーザーを認証すること;
* 認証を処理するために、ユーザーを <Tooltip tip="IDプロバイダー（IdP）: デジタルアイデンティティを保存および管理するサービス。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Identity+Provider">IDプロバイダー</Tooltip> にリダイレクトすること;
* アクティブな <Tooltip tip="シングルサインオン（SSO）: ユーザーが 1 つの applicaton にログインした後、他のアプリケーションにも自動的にログインできるようにするサービス。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Single+Sign-on">シングルサインオン</Tooltip> (SSO) セッションを確認すること;
* 以前に同意が与えられていない場合は、要求された権限レベルについてユーザーの同意を取得すること。

ユーザーを認可するには、アプリからユーザーを認可 URL に送信する必要があります。

<div id="authorization-url-example">
  ### 認可URLの例
</div>

export const codeExample1 = `https://{yourDomain}/authorize?
    response_type=YOUR_RESPONSE_TYPE&
    response_mode=form_post&
    client_id={yourClientId}&
    redirect_uri={https://yourApp/callback}&
    scope=SCOPE&
    state=STATE&
    nonce=NONCE`;

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

<div id="parameters">
  ### パラメータ
</div>

| Parameter Name  | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `response_type` | Auth0 が返す認証情報の種類 (code または token) を示します。Implicit Flow では、値として `id_token`、`token`、または `id_token token` を指定できます。具体的には、`id_token` は ID トークン を返し、`token` はアクセストークンを返します。                                                                                                                                                                                                                                                                                                                                                            |
| `response_mode` | レスポンスパラメータの返却方法を指定します。セキュリティ上の理由から、値は `form_post` にする必要があります。このモードでは、レスポンスパラメータは HTML form の値としてエンコードされ、HTTP POST メソッドで送信される `application/x-www-form-urlencoded` 形式の本文に含まれます。                                                                                                                                                                                                                                                                                                                                                   |
| `client_id`     | あなたのアプリケーションの Client ID です。この値は [アプリケーションの設定](https://manage.auth0.com/#/applications/\{yourClientId}/settings) で確認できます。                                                                                                                                                                                                                                                                                                                                                                                                        |
| `redirect_uri`  | ユーザーが認可を付与した後に、Auth0 がブラウザーをリダイレクトする先の URL です。この URL は、[Application Settings](https://manage.auth0.com/#/Applications/\{yourClientId}/settings) で有効なコールバック URL として指定する必要があります。<br /><br />**警告:** [OAuth 2.0 Specification](https://tools.ietf.org/html/rfc6749#section-3.1.2) に従い、Auth0 はハッシュ以降の内容をすべて削除し、フラグメントは考慮しません。                                                                                                                                                                                                       |
| `scope`         | 認可をリクエストする [スコープ](/docs/ja-jp/get-started/apis/scopes) を指定します。これにより、どのクレーム (またはユーザー属性) を返すかが決まります。複数指定する場合はスペースで区切る必要があります。`profile` や `email` など、ユーザーに関する任意の [standard OpenID Connect (OIDC) スコープ](https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims)、[namespaced format](/docs/ja-jp/secure/tokens/json-web-tokens/create-custom-claims) に準拠した [custom claims](/docs/ja-jp/secure/tokens/json-web-tokens/json-web-token-claims#custom-claims)、または対象 API がサポートする任意の スコープ (たとえば `read:contacts`) をリクエストできます。 |
| `state`         | (推奨) アプリが最初の request に追加し、Auth0 がアプリケーションへのリダイレクト時に含める、不透明な任意の英数字文字列です。この値を使用してクロスサイトリクエストフォージェリ (CSRF) 攻撃を防ぐ方法については、[Mitigate CSRF Attacks With State Parameters](/docs/ja-jp/secure/attack-protection/state-parameters) を参照してください。                                                                                                                                                                                                                                                                                            |
| `nonce`         | (`response_type` に `id_token token` が含まれる場合は必須、それ以外は推奨) アプリが最初の request に追加し、Auth0 が ID トークン内に含める、暗号学的にランダムな文字列です。[トークンのリプレイ攻撃を防ぐために使用されます](/docs/ja-jp/get-started/authentication-and-authorization-flow/implicit-flow-with-form-post/mitigate-replay-attacks-when-using-the-implicit-flow)。                                                                                                                                                                                                                                   |
| `connection`    | (任意) ユーザーが特定の 接続 を使ってサインインするよう指定します。たとえば、値として `github` を渡すと、ユーザーは GitHub アカウントでログインするために直接 GitHub に移動します。指定しない場合、ユーザーには構成済みのすべての 接続 が表示された Auth0 Lock 画面 が表示されます。構成済みの 接続 の一覧は、アプリケーションの **Connections** タブで確認できます。                                                                                                                                                                                                                                                                                                             |
| `organization`  | (任意) ユーザーの認証時に使用する organization の ID です。指定しない場合、アプリケーションで **Display Organization Prompt** を表示する設定になっていれば、ユーザーは認証時に organization名 を入力できます。                                                                                                                                                                                                                                                                                                                                                                                       |
| `invitation`    | (任意) organization 招待の ticket ID です。[Organization にメンバーを招待する](/docs/ja-jp/manage-users/organizations/configure-organizations/invite-members) 場合、ユーザーが招待を受け入れる際に、アプリケーションは `invitation` と `organization` のキーと値のペアを渡して、招待の受け入れを処理する必要があります。                                                                                                                                                                                                                                                                                        |

例として、アプリに login を追加する際の認可 URL 用 HTML スニペットは次のようになります。

export const codeExample2 = `<a href="https://{yourDomain}/authorize?
  response_type=id_token token&
  response_mode=form_post&
  client_id={yourClientId}&
  redirect_uri={https://yourApp/callback}&
  scope=read:tests&
  state=xyzABC123&
  nonce=eq...hPmz">
  ログイン
</a>`;

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

<div id="response">
  ### レスポンス
</div>

問題なく進むと、`HTTP 302` レスポンスが返されます。要求した資格情報はレスポンスボディにエンコードされています：

```json lines theme={null}
HTTP/1.1 302 Found
Content-Type: application/x-www-form-urlencoded
id_token=eyJ...acA&
state=xyzABC123
```

返される値は、`response_type` に何を指定したかによって異なる点に注意してください。

| Response Type   | Components                                           |
| --------------- | ---------------------------------------------------- |
| id\_token       | ID トークン                                              |
| token           | アクセストークン (`expires_in` と `token_type` の値を含む)         |
| id\_token token | ID トークン、アクセストークン (`expires_in` と `token_type` の値を含む) |

Auth0 は、認可 URL の呼び出し時に含めた state 値も返します。

<Warning>
  トークンは保存する前に検証してください。方法については、[ID トークンを検証する](/docs/ja-jp/secure/tokens/id-tokens/validate-id-tokens) と [アクセストークンを検証する](/docs/ja-jp/secure/tokens/access-tokens/validate-access-tokens) を参照してください。
</Warning>

ID トークンには、デコードして抽出する必要のあるユーザー情報が含まれています。

<div id="use-cases">
  ## ユースケース
</div>

<div id="basic-authentication-request">
  ### 基本的な認証リクエスト
</div>

この例では、ステップ 1 でユーザーを認証する際に送信できる、最も基本的なリクエストを示します。Auth0 のログイン画面が表示され、設定済みの任意の接続を使ってユーザーがサインインできます。

export const codeExample3 = `https://{yourDomain}/authorize?
    response_type=id_token&
    response_mode=form_post&
    client_id={yourClientId}&
    redirect_uri={https://yourApp/callback}&
    nonce=NONCE`;

<AuthCodeBlock children={codeExample3} language="http" />

これにより、ID トークンが返されます。この ID トークンはリダイレクト URL から取得できます。

<div id="request-users-name-and-profile-picture">
  ### ユーザーの名前とプロフィール画像を要求する
</div>

この例では、通常のユーザー認証に加えて、名前やプロフィール画像などの追加のユーザー情報を要求する方法を示します。

ユーザーの名前とプロフィール画像を要求するには、ユーザーの認可時に適切なスコープを追加する必要があります。

export const codeExample4 = `https://{yourDomain}/authorize?
    response_type=id_token token&
    response_mode=form_post&
    client_id={yourClientId}&
    redirect_uri={https://yourApp/callback}&
    scope=openid%20name%20picture&
    state=STATE&
    nonce=NONCE`;

<AuthCodeBlock children={codeExample4} language="http" />

これで、ID トークンに要求した name とプロフィール画像のクレームが含まれます。ID トークンをデコードすると、次のようになります。

```json lines theme={null}
{
  "name": "jerrie@...",
  "picture": "https://s.gravatar.com/avatar/6222081fd7dcea7dfb193788d138c457?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fje.png",
  "iss": "https://auth0pnp.auth0.com/",
  "sub": "auth0|581...",
  "aud": "xvt...",
  "exp": 1478113129,
  "iat": 1478077129
}
```

<div id="request-user-log-in-with-github">
  ### GitHub でユーザーをログインさせる
</div>

通常のユーザー認証に加えて、この例では GitHub のようなソーシャルアイデンティティプロバイダーにユーザーを直接リダイレクトする方法を示します。この例を機能させるには、[Auth0 Dashboard > 認証 > Social](https://manage.auth0.com/#/connections/social) に移動して、適切な接続を設定する必要があります。接続名は **設定** タブで確認してください。

ユーザーを GitHub のログイン画面に直接送るには、ユーザーを認可する際に `connection` パラメーターを渡し、その値を接続名 (この場合は `github`) に設定する必要があります。

export const codeExample5 = `https://{yourDomain}/authorize?
    response_type=id_token token&
    response_mode=form_post&
    client_id={yourClientId}&
    redirect_uri={https://yourApp/callback}&
    scope=openid%20name%20picture&
    state=STATE&
    nonce=NONCE&
    connection=github`;

<AuthCodeBlock children={codeExample5} language="http" />

これで、ID トークンには GitHub から返されたユーザー固有の ID を持つ `sub` クレームが含まれるようになります。ID トークンをデコードすると、次のような内容になります。

```json lines theme={null}
{
  "name": "Jerrie Pelser",
  "nickname": "jerriep",
  "picture": "https://avatars.githubusercontent.com/u/1006420?v=3",
  "iss": "https://auth0pnp.auth0.com/",
  "sub": "github|100...",
  "aud": "xvt...",
  "exp": 1478114742,
  "iat": 1478078742
}
```

<div id="learn-more">
  ## 詳細情報
</div>

* [OAuth 2.0 認可フレームワーク](/docs/ja-jp/authenticate/protocols/oauth)
* [OpenID Connect プロトコル](/docs/ja-jp/authenticate/protocols/openid-connect-protocol)
* [トークン](/docs/ja-jp/secure/tokens)
* [Implicit Flow 使用時のリプレイ攻撃を防ぐ](/docs/ja-jp/get-started/authentication-and-authorization-flow/implicit-flow-with-form-post/mitigate-replay-attacks-when-using-the-implicit-flow)
* [Single-Page Web Applications を登録する](/docs/ja-jp/get-started/auth0-overview/create-applications/single-page-web-apps)
* [グラントタイプを更新する](/docs/ja-jp/get-started/applications/update-grant-types)
