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

> 認可エラーイベント用のカスタムエラーページを作成する方法を説明します。

# エラーページのカスタマイズ

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

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

認可エラーが発生した際に callback URL が有効であれば、<Tooltip tip="認可サーバー: ユーザーのアクセス境界の定義に関与する集中的なサーバーです。たとえば、認可サーバーはユーザーが利用できるデータ、タスク、機能を制御できます。" cta="用語集を見る" href="/ja/docs/glossary?term=Authorization+Server">認可サーバー</Tooltip>は、適切な error パラメーターと state パラメーターを callback URL に返します。callback URL が無効な場合は、アプリケーションに[デフォルトの Auth0 エラーページ](/ja/docs/authenticate/login/auth0-universal-login/error-pages)が表示されます。

また、callback URL が無効な場合以外でも、アプリケーションにデフォルトの Auth0 エラーページが表示されることがあります。たとえば、次のような場合です。

* Auth0 Authentication API の [Login エンドポイント](https://auth0.com/docs/api/authentication#login)を呼び出すときに、必須パラメーターが不足している。
* ユーザーが期限切れのパスワードリセットリンクを開く (Classic Login を使用している場合) 。
* ユーザーがブックマークしたログインページにアクセスし、[デフォルトのログインルート](/ja/docs/authenticate/login/auth0-universal-login/configure-default-login-routes)が指定されていない。

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

カスタムエラーページを設定した場合、認可サーバーは URL にクエリ文字列として付加されたパラメーターを返します。

| Parameter           | Description                     |
| ------------------- | ------------------------------- |
| `client_id`         | Auth0 アプリケーションの識別子。             |
| `connection`        | エラー発生時に使用されていた接続。               |
| `lang`              | エラー発生時に使用する言語として設定されていた言語。      |
| `error`             | エラーコード。                         |
| `error_description` | エラーの説明。                         |
| `tracking`          | Auth0 が内部ログでエラーを特定するために使用する識別子。 |

返されるパラメーターはエラーの種類によって異なり、リクエストごとに異なります。たとえば、エラーとなったリクエストに `client_id` が含まれていなかった場合、認可サーバーは `client_id` パラメーターを返しません。

<div id="display-a-custom-error-page">
  ## カスタムエラーページを表示する
</div>

カスタムエラーページを表示するには、次の 2 つの方法があります。

1. Auth0 Dashboard または Auth0 Management API を使用して、ユーザーをカスタムエラーページにリダイレクトします。
2. Management API を使用して、Auth0 がカスタムエラーページを代わりにレンダリングするよう設定します。

<div id="redirect-users-to-a-custom-error-page-using-the-dashboard">
  ### Dashboard を使用してユーザーをカスタムエラーページにリダイレクトする
</div>

Dashboard を使用して、Auth0 がユーザーをカスタムエラーページにリダイレクトするよう設定します。

1. [Auth0 Dashboard > Tenant Settings](https://manage.auth0.com/#/tenant/) に移動します。
2. **Error Pages** セクションを探します。
3. **Redirect users to your own error page** オプションを選択します。
4. ユーザーに表示するエラーページの URL を入力し、**Save** を選択します。

<div id="redirect-users-to-a-custom-error-page-using-the-management-api">
  ### Management API を使用してユーザーをカスタムエラーページにリダイレクトする
</div>

<Tooltip tip="Management API: お客様が管理タスクを実行するためのプロダクトです。" cta="用語集を見る" href="/ja/docs/glossary?term=Management+API">Management API</Tooltip> の [Update Tenant Settings](https://auth0.com/docs/api/management/v2/#!/Tenants/patch_settings) エンドポイントを使用します。`{mgmtApiAccessToken}` プレースホルダーの値を Management API の <Tooltip tip="Access Token: API へのアクセスに使用される認可資格情報で、不透明な文字列または JWT の形式を取ります。" cta="用語集を見る" href="/ja/docs/glossary?term=Access+Token">アクセストークン</Tooltip> に置き換え、JSON 本文の `url` フィールドの値を、エラーページの場所を指すように更新します。

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request PATCH \
    --url 'https://{yourDomain}/api/v2/tenants/settings' \
    --header 'authorization: Bearer {mgmtApiAccessToken}' \
    --header 'content-type: application/json' \
    --data '{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings");
  var request = new RestRequest(Method.PATCH);
  request.AddHeader("authorization", "Bearer {mgmtApiAccessToken}");
  request.AddHeader("content-type", "application/json");
  request.AddParameter("application/json", "{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}", 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}/api/v2/tenants/settings"

  	payload := strings.NewReader("{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}")

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

  	req.Header.Add("authorization", "Bearer {mgmtApiAccessToken}")
  	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.patch("https://{yourDomain}/api/v2/tenants/settings")
    .header("authorization", "Bearer {mgmtApiAccessToken}")
    .header("content-type", "application/json")
    .body("{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}")
    .asString();
  ```

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

  var options = {
    method: 'PATCH',
    url: 'https://{yourDomain}/api/v2/tenants/settings',
    headers: {
      authorization: 'Bearer {mgmtApiAccessToken}',
      'content-type': 'application/json'
    },
    data: {error_page: {html: '', show_log_link: false, url: 'http://www.example.com'}}
  };

  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}/api/v2/tenants/settings",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "PATCH",
    CURLOPT_POSTFIELDS => "{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}",
    CURLOPT_HTTPHEADER => [
      "authorization: Bearer {mgmtApiAccessToken}",
      "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 = "{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}"

  headers = {
      'authorization': "Bearer {mgmtApiAccessToken}",
      'content-type': "application/json"
      }

  conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", 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}/api/v2/tenants/settings")

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

  request = Net::HTTP::Patch.new(url)
  request["authorization"] = 'Bearer {mgmtApiAccessToken}'
  request["content-type"] = 'application/json'
  request.body = "{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}"

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

| 値                       | 説明                                                                                                             |
| ----------------------- | -------------------------------------------------------------------------------------------------------------- |
| `MGMT_API_ACCESS_TOKEN` | スコープ `update:tenant_settings` を持つ [Management API のアクセストークン](https://auth0.com/docs/api/management/v2/tokens)。 |
| `show_log_link`         | テナントログ内のエラーへのリンクを表示するかどうかを示します。有効な値は `true` と `false` です。                                                      |
| `url`                   | リダイレクト先として使用するカスタムエラーページのURL。                                                                                  |

<div id="render-a-custom-error-page">
  ### カスタムエラーページを表示する
</div>

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  Classic Login ウィジェット内でエラーが表示される場合 (パスワードリセットリンクの有効期限切れなど) は、設定済みであっても、Auth0 でホストされるカスタムエラーページは表示されません。
</Callout>

Management API の [Update Tenant Settings](https://auth0.com/docs/api/management/v2/#!/Tenants/patch_settings) エンドポイントを使用します。`{mgmtApiAccessToken}` プレースホルダーの値を Management API のアクセストークンに置き換え、JSON ボディの `html` フィールドの値を、ページの HTML を含む文字列に更新します。

Liquid 構文を使用すると、次の変数を含めることができます。

* `{client_id}`
* `{connection}`
* `{lang}`
* `{error}`
* `{error_description}`
* `{tracking}`

<AuthCodeGroup>
  ```bash cURL lines theme={null}
  curl --request PATCH \
    --url https://login.auth0.com/api/v2/tenants/settings \
    --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \
    --header 'content-type: application/json' \
    --data '{"error_page": {"html": "<h1>{{error | escape }} {{error_description | escape }} This error was generated {{'\''now'\'' | date: '\''%Y %h'\''}}.</h1>", "show_log_link": false, "url": ""}}'
  ```

  ```csharp C# lines theme={null}
  var client = new RestClient("https://login.auth0.com/api/v2/tenants/settings");
  var request = new RestRequest(Method.PATCH);
  request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN");
  request.AddHeader("content-type", "application/json");
  request.AddParameter("application/json", "{\"error_page\": {\"html\": \"

  # {{error | escape }} {{error_description | escape }} This error was generated {{'now' | date: '%Y %h'}}.

  \", \"show_log_link\": false, \"url\": \"\"}}", ParameterType.RequestBody);
  IRestResponse response = client.Execute(request);
  ```

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

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

  func main() {

  	url := "https://login.auth0.com/api/v2/tenants/settings"

  	payload := strings.NewReader("{\"error_page\": {\"html\": \"<h1>{{error | escape }} {{error_description | escape }} This error was generated {{'now' | date: '%Y %h'}}.</h1>\", \"show_log_link\": false, \"url\": \"\"}}")

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

  	req.Header.Add("authorization", "Bearer MGMT_API_ACCESS_TOKEN")
  	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 lines theme={null}
  HttpResponse<String> response = Unirest.patch("https://login.auth0.com/api/v2/tenants/settings")
    .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN")
    .header("content-type", "application/json")
    .body("{\"error_page\": {\"html\": \"<h1>{{error | escape }} {{error_description | escape }} This error was generated {{'now' | date: '%Y %h'}}.</h1>\", \"show_log_link\": false, \"url\": \"\"}}")
    .asString();
  ```

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

  var options = {
    method: 'PATCH',
    url: 'https://login.auth0.com/api/v2/tenants/settings',
    headers: {
      authorization: 'Bearer MGMT_API_ACCESS_TOKEN',
      'content-type': 'application/json'
    },
    data: {
      error_page: {
        html: '<h1>{{error | escape }} {{error_description | escape }} This error was generated {{\'now\' | date: \'%Y %h\'}}.</h1>',
        show_log_link: false,
        url: ''
      }
    }
  };

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

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

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://login.auth0.com/api/v2/tenants/settings",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "PATCH",
    CURLOPT_POSTFIELDS => "{\"error_page\": {\"html\": \"<h1>{{error | escape }} {{error_description | escape }} This error was generated {{'now' | date: '%Y %h'}}.</h1>\", \"show_log_link\": false, \"url\": \"\"}}",
    CURLOPT_HTTPHEADER => [
      "authorization: Bearer MGMT_API_ACCESS_TOKEN",
      "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 lines theme={null}
  import http.client

  conn = http.client.HTTPSConnection("login.auth0.com")

  payload = "{\"error_page\": {\"html\": \"<h1>{{error | escape }} {{error_description | escape }} This error was generated {{'now' | date: '%Y %h'}}.</h1>\", \"show_log_link\": false, \"url\": \"\"}}"

  headers = {
      'authorization': "Bearer MGMT_API_ACCESS_TOKEN",
      'content-type': "application/json"
      }

  conn.request("PATCH", "/api/v2/tenants/settings", payload, headers)

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

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

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

  url = URI("https://login.auth0.com/api/v2/tenants/settings")

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

  request = Net::HTTP::Patch.new(url)
  request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN'
  request["content-type"] = 'application/json'
  request.body = "{\"error_page\": {\"html\": \"<h1>{{error | escape }} {{error_description | escape }} This error was generated {{'now' | date: '%Y %h'}}.</h1>\", \"show_log_link\": false, \"url\": \"\"}}"

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

| 値                       | 説明                                                                                                             |
| ----------------------- | -------------------------------------------------------------------------------------------------------------- |
| `MGMT_API_ACCESS_TOKEN` | スコープ `update:tenant_settings` を持つ [Management API のアクセストークン](https://auth0.com/docs/api/management/v2/tokens)。 |
| `show_log_link`         | テナントログ内のエラーへのリンクを表示するかどうかを指定します。有効な値は `true` と `false` です。                                                     |
| `html`                  | 表示するカスタムエラーページの HTML。                                                                                          |

XSS 脆弱性を防ぐには、Liquid の [escape](https://shopify.github.io/liquid/filters/escape/) フィルターと [strip\_html](https://shopify.github.io/liquid/filters/strip_html/) フィルターを使用して、カスタムテンプレートをサニタイズしてください。

<div id="learn-more">
  ## 詳しく見る
</div>

* [Auth0 Universal Login](/ja/docs/authenticate/login/auth0-universal-login)
