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

> パスワードレス接続向けのカスタムSMSゲートウェイを設定する方法を説明します。

# パスワードレス接続向けのカスタムSMSゲートウェイを設定する

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

<Warning>
  このガイドは、パスワードレス接続向けの従来のカスタム SMS 実装について説明するもので、2025 年 3 月より前に作成された Auth0 テナントにのみ適用されます。

  新しいテナントでは、[SMS 電話番号プロバイダーの設定手順](/ja/docs/authenticate/passwordless/authentication-methods/sms-otp#configure-the-phone-provider)に従ってください。
</Warning>

このガイドでは、カスタム SMS ゲートウェイを使用してワンタイムコードを送信する方法を説明します。

デフォルトでは、[パスワードレス SMS 接続](/ja/docs/authenticate/passwordless/authentication-methods/sms-otp) は、ワンタイムコードの送信に [Twilio](https://www.twilio.com) を使用します。ただし、カスタム SMS ゲートウェイがある場合は、そのゲートウェイを使用するように接続を変更できます。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  Auth0 は基本的な SMS 認証をサポートしていません。
</Callout>

1. SMS パスワードレス接続を設定します。手順については、[パスワードレス接続](/ja/docs/authenticate/passwordless) の「Implement Passwordless」セクションを参照してください。
2. [Management API のアクセストークンを取得します](/ja/docs/secure/tokens/access-tokens/management-api-access-tokens)。これは、パスワードレス接続を更新するために Management API を呼び出す際に必要です。
3. [GET Connections](https://auth0.com/docs/api/management/v2#!/Connections/get_connections) エンドポイントを使用して、テナントに関連付けられている接続の情報を取得します。具体的には、後続の API 呼び出しで接続自体を更新するときに使用する、パスワードレス SMS 接続の ID を取得する必要があります。
   次の Management API 呼び出しを実行する前に、`ACCESS_TOKEN` を手順 1 で取得したトークンに必ず置き換えてください。

<AuthCodeGroup>
  ```bash cURL lines theme={null}
  curl --request GET \
    --url https://your-auth0-tenant.com/api/v2/connections \
    --header 'authorization: Bearer {yourAccessToken}'
  ```

  ```csharp C# lines theme={null}
  var client = new RestClient("https://your-auth0-tenant.com/api/v2/connections");
  var request = new RestRequest(Method.GET);
  request.AddHeader("authorization", "Bearer {yourAccessToken}");
  IRestResponse response = client.Execute(request);
  ```

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

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

  func main() {

  	url := "https://your-auth0-tenant.com/api/v2/connections"

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

  	req.Header.Add("authorization", "Bearer {yourAccessToken}")

  	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 response = Unirest.get("https://your-auth0-tenant.com/api/v2/connections")
    .header("authorization", "Bearer {yourAccessToken}")
    .asString();
  ```

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

  var options = {
    method: 'GET',
    url: 'https://your-auth0-tenant.com/api/v2/connections',
    headers: {authorization: 'Bearer {yourAccessToken}'}
  };

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

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

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://your-auth0-tenant.com/api/v2/connections",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => [
      "authorization: Bearer {yourAccessToken}"
    ],
  ]);

  $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("your-auth0-tenant.com")

  headers = { 'authorization': "Bearer {yourAccessToken}" }

  conn.request("GET", "/api/v2/connections", headers=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://your-auth0-tenant.com/api/v2/connections")

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

  request = Net::HTTP::Get.new(url)
  request["authorization"] = 'Bearer {yourAccessToken}'

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

エンドポイントからのレスポンスは、オブジェクトの配列です。各オブジェクトは、テナントに関連付けられた 1 つの接続を表します。
4\. 接続 ID を特定します。手順 2 の [GET Connections エンドポイント](https://auth0.com/docs/api/management/v2#!/Connections/get_connections) から返されたオブジェクト配列を確認すると、パスワードレス接続に対応する ID を確認できます。
パスワードレス接続に該当するオブジェクトを見つけるには、`"name": "sms"` プロパティを検索します。その接続には現在、セットアップ時に指定した Twilio の情報が表示されていることを確認してください。

```json lines expandable theme={null}
   [
       {
           "id": "con_UX85K7K0N86INi9U",
           "options": {
               "disable_signup": false,
               "name": "sms",
               "twilio_sid": "TWILIO_SID",
               "twilio_token": "TWILIO_AUTH_TOKEN",
               "from": "+15555555555",
               "syntax": "md_with_macros",
               "template": "Your SMS verification code is: @@password@@",
               "totp": {
                   "time_step": 300,
                   "length": 6
               },
               "messaging_service_sid": null,
               "brute_force_protection": true
           },
           "strategy": "sms",
           "name": "sms",
           "is_domain_connection": false,
           "realms": [
               "sms"
           ],
       }
   ]
```

5. 接続を更新します。これを行うには、[Update a Connection endpoint](https://auth0.com/docs/api/management/v2#!/Connections/patch_connections_by_id) に PATCH リクエストを送信します。具体的には、SMSゲートウェイ に関する情報を指定するために、接続の `options` オブジェクトを更新します。

   <Warning>
     呼び出しのたびに `options` オブジェクト全体を送信する必要があります。そうしないと、後続の呼び出しで含まれていない既存のデータが上書きされます。
   </Warning>

   次の変更を行います。

   * `twilio_sid` パラメーターと `twilio_token` パラメーターを削除する
   * `provider` パラメーターを追加し、`sms_gateway` に設定する
   * `gateway_url` パラメーターを追加し、SMSゲートウェイ の URL に設定する。Auth0 がメッセージを代理送信する際にこの gateway を使用できるようにするには、Auth0 からこの URL にアクセスできる必要があります。

   ペイロードは次のようになります。

   ```json lines theme={null}
   {
       "options": {
         "strategy": "sms",
         "provider": "sms_gateway",
         "gateway_url": "{urlOfYourGateway}",
         "from": "+1 234 567",
         "template": "Your verification code is: @@password@@",
         "brute_force_protection": true,
         "forward_req_info": "true",
         "disable_signup": false,
         "name": "sms",
         "syntax": "md_with_macros",
         "totp": {
           "time_step": 300,
           "length": 6
         }
       },
       "is_domain_connection": false,
   }
   ```

<div id="authenticated-requests">
  ## 認証付きリクエスト
</div>

SMS Gateway がトークンベースの認証付きリクエストを受け付ける場合は、以下を `options` オブジェクトに追加できます。

```json lines theme={null}
"gateway_authentication": {
    "method": "bearer",
    "subject": "urn:Auth0",
    "audience": "urn:MySmsGateway",
    "secret": "MySecretToSignTheToken",
    "secret_base64_encoded": false
}
```

`options` オブジェクトに `gateway_authentication` を含めると、Auth0 は SMS ゲートウェイにリクエストを送信するたびに、`Authorization` ヘッダーに [JSON Web Token](/ja/docs/secure/tokens/json-web-tokens) を追加します。このトークンには `gateway_authentication.subject` と `gateway_authentication.audience` の値が含まれ、`gateway_authentication.secret` で署名されます。

シークレットが base64url エンコードされている場合は、`secret_base64_encoded` を `true` に設定します。

接続を更新すると、ユーザーが <Tooltip tip="パスワードレス: 最初の要素としてパスワードに依存しない認証方式です。" cta="用語集を見る" href="/ja/docs/glossary?term=Passwordless">パスワードレス</Tooltip> 接続でサインアップまたはログインするたびに、Auth0 は以下の情報を SMS ゲートウェイに送信します。

```json lines theme={null}
{
  "recipient": "+1 399 999",
  "body": "Your verification code is: 12345",
  "sender": "+1 234 567"
}
```

`options` オブジェクトの `forward_req_info` プロパティを `true` に設定すると、ゲートウェイはパスワードレスのプロセスを開始した HTTP リクエストの情報も受け取ります。これには、`/passwordless/start` を呼び出すクライアントの IP アドレスと User Agent が含まれます。

```json lines theme={null}
{
  "recipient": "+1 399 999",
  "body": "Your verification code is: 12345",
  "sender": "+1 234 567",
  "req" : { 
      "ip" : "167.56.227.117",
      "user-agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36"
       }
}
```

<div id="error-handling">
  ## エラー処理
</div>

Auth0 は SMSゲートウェイ から返される HTTP ステータスコードのみを参照し、それ以外のレスポンス (例: レスポンスボディやレスポンスタイプ) は無視します。

SMSゲートウェイ が 200 以外の HTTP コードを返した場合、`/passwordless/start` エンドポイントは HTTP 400 コードと、次のようなレスポンスを返します。

```json lines theme={null}
{
 "error":"sms_provider_error",
 "error_description":"Unexpected response while calling the SMS gateway: <HTTP Code Returned by the SMS Gateway>"}
}
```

SMSゲートウェイ が HTTP 401 を返した場合、`error_description` は **Authentication failed while calling the SMS gateway: 401** になります。 (エラーの説明文は、予告なくいつでも変更される可能性がある点にご注意ください。)

Auth0 は、カスタム SMSゲートウェイ への HTTP 呼び出しに 30 秒のタイムアウトを設定しています。SMSゲートウェイ がこの時間内に応答しない場合、`/passwordless/start` エンドポイントも HTTP 400 コードを返します。レスポンスは上記の形式となり、`error_description` フィールドは **Timeout while calling the SMS gateway: \<Timeout Code>** になります。 (繰り返しになりますが、エラーの説明文は予告なくいつでも変更される可能性があります。)
