> ## 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) + "*****マスク済み*****";
          }
          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](/ja/docs/get-started/authentication-and-authorization-flow/implicit-flow-with-form-post) を参照してください。

Form Post を使用した Implicit Flow は、ログイン専用のユースケースで使用してください。ユーザーのログイン時に <Tooltip tip="アクセストークン: API へのアクセスに使用される、不透明な文字列または JWT 形式の認可資格情報。" cta="用語集を表示" href="/ja/docs/glossary?term=access+tokens">アクセストークン</Tooltip> をリクエストして API を呼び出す必要がある場合は、PKCE を使用する認可コードフローを使用してください。詳細については、[Authorization Code Flow with Proof Key for Code Exchange (PKCE](/ja/docs/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): フローを実装する最も簡単な方法で、煩雑な処理の大半を担います。Auth0 の JavaScript SDK を使用する場合は、ご利用のアーキテクチャに適した軽減策を実装していることを確認してください。詳細については、[Auth0.js Reference](/ja/docs/libraries/auth0js) を参照してください。
* [Authentication API](https://auth0.com/docs/api/authentication): 独自のソリューションを構築する場合は、このまま読み進めて API を直接呼び出す方法を確認してください。

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

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

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

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

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

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

* ユーザーを認証する;
* 認証を処理するために、ユーザーを <Tooltip tip="IDプロバイダー（IdP）: デジタルアイデンティティを保存および管理するサービス。" cta="用語集を見る" href="/ja/docs/glossary?term=Identity+Provider">IDプロバイダー</Tooltip> にリダイレクトする;
* 有効な <Tooltip tip="シングルサインオン（SSO）: ユーザーが 1 つのアプリケーションにログインすると、他のアプリケーションにも自動的にログインされるサービス。" cta="用語集を見る" href="/ja/docs/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` にする必要があります。このモードでは、レスポンスパラメーターは HTTP POST メソッドで送信される HTML フォームの値としてエンコードされ、`application/x-www-form-urlencoded` 形式でボディに格納されます。                                                                                                                                                                                                                                                                                                                  |
| `client_id`     | アプリケーションの クライアントID です。この値は [アプリケーションの設定](https://manage.auth0.com/#/applications/\{yourClientId}/settings) で確認できます。                                                                                                                                                                                                                                                                                                                                                                               |
| `redirect_uri`  | ユーザーが認可を付与した後に、Auth0 がブラウザーをリダイレクトする URL です。この URL は、[Application Settings](https://manage.auth0.com/#/Applications/\{yourClientId}/settings) で有効な callback URL として指定する必要があります。<br /><br />**警告:** [OAuth 2.0 Specification](https://tools.ietf.org/html/rfc6749#section-3.1.2) に従い、Auth0 はハッシュ以降のすべてを削除し、フラグメントは *いっさい考慮しません*。                                                                                                                                                                   |
| `scope`         | 認可をリクエストする [スコープ](/ja/docs/get-started/apis/scopes) を指定します。これにより、返されるクレーム (またはユーザー属性) が決まります。各値はスペースで区切る必要があります。`profile` や `email` などのユーザーに関する [標準 OpenID Connect (OIDC) scopes](https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims)、[namespaced format](/ja/docs/secure/tokens/json-web-tokens/create-custom-claims) に準拠した [カスタムクレーム](/ja/docs/secure/tokens/json-web-tokens/json-web-token-claims#custom-claims)、または対象 API がサポートする任意のスコープ (たとえば `read:contacts`) をリクエストできます。 |
| `state`         | (推奨) アプリが最初のリクエストに追加し、Auth0 がアプリケーションにリダイレクトする際に含める、不透明な任意の英数字文字列です。この値を使用して Cross-site Request Forgery (CSRF) 攻撃を防ぐ方法については、[Mitigate CSRF Attacks With State Parameters](/ja/docs/secure/attack-protection/state-parameters) を参照してください。                                                                                                                                                                                                                                                          |
| `nonce`         | (`response_type` に `id_token token` が含まれる場合は必須、それ以外では推奨) アプリが最初のリクエストに追加し、Auth0 が IDトークン に含める、暗号学的にランダムな文字列です。[トークンのリプレイ攻撃を防ぐために使用されます](/ja/docs/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`  | (任意) ユーザーの認証時に使用する組織の ID です。指定しない場合、アプリケーションで **Display Organization Prompt** が設定されていれば、ユーザーは認証時に組織名を入力できます。                                                                                                                                                                                                                                                                                                                                                                                      |
| `invitation`    | (任意) 組織への招待の ticket ID です。[組織にメンバーを招待する](/ja/docs/manage-users/organizations/configure-organizations/invite-members) 場合、ユーザーが招待を承諾したときに、アプリケーションは `invitation` と `organization` のキーと値のペアを転送して、招待の承諾を処理する必要があります。                                                                                                                                                                                                                                                                                  |

例として、アプリにログインを追加する際の認可 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` として何をリクエストしたかによって異なることに注意してください。

| レスポンスタイプ        | コンポーネント                                             |
| --------------- | --------------------------------------------------- |
| id\_token       | IDトークン                                              |
| token           | アクセストークン (`expires_in` と `token_type` の値を含む)        |
| id\_token token | IDトークン、アクセストークン (`expires_in` と `token_type` の値を含む) |

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

<Warning>
  保存する前にトークンを検証してください。方法については、[IDトークンを検証する](/ja/docs/secure/tokens/id-tokens/validate-id-tokens) および [アクセストークンを検証する](/ja/docs/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トークン が返され、リダイレクト 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` クレーム と `picture` クレーム が含まれます。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 などのソーシャル IDプロバイダーにユーザーを直接リダイレクトする方法を示します。この例を機能させるには、[Auth0 Dashboard > Authentication > Social](https://manage.auth0.com/#/connections/social) に移動し、適切な接続を設定する必要があります。接続名は **Settings** タブで確認してください。

ユーザーを 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 認可フレームワーク](/ja/docs/authenticate/protocols/oauth)
* [OpenID Connect プロトコル](/ja/docs/authenticate/protocols/openid-connect-protocol)
* [トークン](/ja/docs/secure/tokens)
* [Implicit Flow 使用時のリプレイ攻撃を軽減する](/ja/docs/get-started/authentication-and-authorization-flow/implicit-flow-with-form-post/mitigate-replay-attacks-when-using-the-implicit-flow)
* [シングルページ Web アプリケーションを登録する](/ja/docs/get-started/auth0-overview/create-applications/single-page-web-apps)
* [グラントタイプを更新する](/ja/docs/get-started/applications/update-grant-types)
