> ## Documentation Index
> Fetch the complete documentation index at: https://auth0.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 組織の動作を定義する

> Auth0 Organizations機能のアプリケーション内での組織の動作を定義する方法について説明します。

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) + "*****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>;
};

Auth0でアプリケーションを表す場合には、アプリケーションが対応するべきユーザーの種類を指定することができます。個人による個人アカウントへのログインに対応するアプリケーションもあれば、[組織](/docs/ja-jp/manage-users/organizations/organizations-overview)のメンバーによる使用が目的のものもあります。それらの両方に対応するものもあります。これは組織の動作と呼ばれ、Auth0に接続するアプリケーションのそれぞれに設定することができます。

たとえば、アプリケーションには以下を設定することができます。

* 汎用のマーケティング用ランディングページに\*\*［ログイン］\*\* ボタンを提供して、組織を使わずに、ユーザーをAuth0のログインフローに送る。
* B2B顧客のそれぞれに個別のURL（Acmeユーザーであれば`acme.yourcompany.com`など）があり、ユーザーが組織を使ってAuth0 にリダイレクトされ、Acmeの<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=single-sign-on" tip="シングルサインオン（SSO）: ユーザーが1つのアプリケーションにログインした後、そのユーザーを他のアプリケーションに自動的にログインさせるサービス。" cta="用語集の表示">SSO</Tooltip>の［ログイン］ボタンが表示される。

これらのシナリオに合わせて組織の動作を定義することができます。また、組織の動作として、アプリケーションで組織の提供を必須にして、ユーザーが誤って組織を使わないAuth0へ送られた場合、組織の名前を入力できるプロンプトが表示されるように定義することもできます。

組織の動作は<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=auth0-dashboard" tip="Auth0 Dashboard: サービスを構成するためのAuth0の主製品。" cta="用語集の表示">Auth0 Dashboard</Tooltip>または<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=management-api" tip="Management API: 顧客が管理タスクを実行できるようにするための製品。" cta="用語集の表示">Management API</Tooltip>を使って定義できます。

## Auth0 Dashboard

Auth0 Dashboardを使用して組織の動作を定義するには、以下を行います。

1. [［Auth0 Dashboard］>［Applications（アプリケーション）］](https://manage.auth0.com/#/applications)に移動して、組織を構成したいアプリケーションを選択します。
2. **［Organizations（組織）］** ビューを選択して、適切な設定を構成します。

| フィールド        | 説明                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           | APIマッピング                                                                                                                                                                                                                                  |
| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **ユーザーのタイプ** | どのカテゴリーのユーザーがアプリケーションにログインできるかを決定します。<br /><br />オプションには以下が含まれます：<ul><li>**個人**：ユーザーは、個人のアカウントでサインアップでき、アプリケーションに直接ログインできます。個人のユーザーはOrganizationを使用してログインできません。</li><li>**ビジネスユーザー**：ログインするためには、ユーザーはOrganizationのメンバーでなければなりません。選択した場合、Organizationを提供してユーザーを`/authorize`エンドポイントにリダイレクトするか、またはOrganizationのプロンプトのためにログインフローを設定する必要があります。</li><li>**両方**：ユーザーは、Organizationメンバーとしてログインするか、または個人のアカウントでサインアップできます。</li></ul>                                                                  | \_\_ユーザーのタイプ\_\_のマッピング先`organization_usage`<br /><br />オプション：<ul><li>\_\_個人\_\_のマッピング先`deny`</li><li> \_\_ビジネスユーザー\_\_のマッピング先`require`</li><li>\_\_両方\_\_のマッピング先`allow`</li></ul>                                                         |
| **ログインフロー**  | アプリケーションにアクセスしたときにユーザーに表示する最初のログインプロンプトを決定します。ユーザーのタイプがビジネスユーザーまたは両方に設定されている場合のみ、このフィールドを構成できます。<br /><br />オプションは次のとおりです： <ul><li>**資格情報のプロンプト**：ユーザーは最初にログインの資格情報を提供するように求められます。ログイン後、ユーザーはOrganizationを選択できます。</li><li>**Organizationのプロンプト**：ユーザーは最初にOrganizationを選択するように求められます。その後、ログインするための資格情報を提供できます。ユーザーのタイプがビジネスユーザーに設定されている場合のみ、このオプションを使用できます。</li><li>**プロンプトなし**：Auth0は、ユーザーに提供するログインプロンプトを規定していません。代わりに、あなたのアプリケーションが、適切なプロンプトを表示するために、Auth0に必要なパラメーターを送信する責任を負います。</li></ul> | **ログインフロー** のマッピング先`organization_require_behavior`<br /><br />オプション:<ul><li>\_\_資格情報のプロンプト\_\_のマッピング先`post_login_prompt`</li><li> \_\_Organizationのプロンプト\_\_のマッピング先`pre_login_prompt`</li><li>\_\_プロンプトなし\_\_のマッピング先`no_prompt`</li></ul> |

3. **［Save Changes（変更の保存）］** を選択します。

## Mangement API

[クライアント更新エンドポイント](/docs/ja-jp/api/management/v2#!/Clients/patch_clients_by_id)に`PATCH`呼び出しを行います。`client_id`、`mgmt_api_access_token`、`organization_usage`、および`organization_require_behavior`のプレースホルダーをそれぞれクライアントID、Management APIのアクセストークン、組織の使用オプション、組織の動作オプションに置き換えます。

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request PATCH \
    --url 'https://{yourDomain}/api/v2/clients/CLIENT_ID' \
    --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \
    --header 'cache-control: no-cache' \
    --header 'content-type: application/json' \
    --data '{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/api/v2/clients/CLIENT_ID");
  var request = new RestRequest(Method.PATCH);
  request.AddHeader("content-type", "application/json");
  request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN");
  request.AddHeader("cache-control", "no-cache");
  request.AddParameter("application/json", "{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }", 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/clients/CLIENT_ID"

  	payload := strings.NewReader("{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }")

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

  	req.Header.Add("content-type", "application/json")
  	req.Header.Add("authorization", "Bearer MGMT_API_ACCESS_TOKEN")
  	req.Header.Add("cache-control", "no-cache")

  	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/clients/CLIENT_ID")
    .header("content-type", "application/json")
    .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN")
    .header("cache-control", "no-cache")
    .body("{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }")
    .asString();
  ```

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

  var options = {
    method: 'PATCH',
    url: 'https://{yourDomain}/api/v2/clients/CLIENT_ID',
    headers: {
      'content-type': 'application/json',
      authorization: 'Bearer MGMT_API_ACCESS_TOKEN',
      'cache-control': 'no-cache'
    },
    data: {
      organization_usage: 'ORG_USAGE',
      organization_require_behavior: 'ORG_REQUIRE_BEHAVIOR'
    }
  };

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

  ```objc Obj-C theme={null}
  #import <Foundation/Foundation.h>

  NSDictionary *headers = @{ @"content-type": @"application/json",
                             @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN",
                             @"cache-control": @"no-cache" };
  NSDictionary *parameters = @{ @"organization_usage": @"ORG_USAGE",
                                @"organization_require_behavior": @"ORG_REQUIRE_BEHAVIOR" };

  NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/clients/CLIENT_ID"]
                                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                     timeoutInterval:10.0];
  [request setHTTPMethod:@"PATCH"];
  [request setAllHTTPHeaderFields:headers];
  [request setHTTPBody:postData];

  NSURLSession *session = [NSURLSession sharedSession];
  NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                              completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                  if (error) {
                                                      NSLog(@"%@", error);
                                                  } else {
                                                      NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                      NSLog(@"%@", httpResponse);
                                                  }
                                              }];
  [dataTask resume];
  ```

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

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://{yourDomain}/api/v2/clients/CLIENT_ID",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "PATCH",
    CURLOPT_POSTFIELDS => "{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }",
    CURLOPT_HTTPHEADER => [
      "authorization: Bearer MGMT_API_ACCESS_TOKEN",
      "cache-control: no-cache",
      "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 = "{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }"

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

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

  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["content-type"] = 'application/json'
  request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN'
  request["cache-control"] = 'no-cache'
  request.body = "{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }"

  response = http.request(request)
  puts response.read_body
  ```

  ```swift Swift theme={null}
  import Foundation

  let headers = [
    "content-type": "application/json",
    "authorization": "Bearer MGMT_API_ACCESS_TOKEN",
    "cache-control": "no-cache"
  ]
  let parameters = [
    "organization_usage": "ORG_USAGE",
    "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR"
  ] as [String : Any]

  let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

  let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/api/v2/clients/CLIENT_ID")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
  request.httpMethod = "PATCH"
  request.allHTTPHeaderFields = headers
  request.httpBody = postData as Data

  let session = URLSession.shared
  let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
      print(error)
    } else {
      let httpResponse = response as? HTTPURLResponse
      print(httpResponse)
    }
  })

  dataTask.resume()
  ```
</AuthCodeGroup>

| 値                               | 説明                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `CLIENT_ID`                     | Organizationの動作を追加したいアプリケーションのIDです。                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `MGMT_API_ACCESS_TOKEN`         | `update:clients`スコープのある[Management APIのアクセストークン](/docs/ja-jp/tokens/management-api-access-tokens)です。                                                                                                                                                                                                                                                                                                                                                                     |
| `ORGANIZATION_USAGE`            | ユーザーがOrganizationにログインすることに、アプリケーションが対応するか決定します。オプションには以下が含まれます。<ul><li>`deny`：（デフォルト）ユーザーはOrganizationを使用してログインできません。</li><li>`allow`：ユーザーはOrganizationを使用して、または使用せずにログインできます。選択した場合、`/authorize`エンドポイントへのリダイレクトでユーザーにOrganizationを提供する必要があります。</li><li>`require`：ユーザーはOrganizationを使用してログインしなければなりません。選択した場合、`/authorize`エンドポイントへのリダイレクトでユーザーにOrganizationを提供するか、`organization_require_behavior`を`pre_login_prompt`に設定し、ユーザーがOrganizationを選択してログインできるようにします。</li></ul> |
| `ORGANIZATION_REQUIRE_BEHAVIOR` | アプリケーションへのアクセスでユーザーに提供するログインフローを決定します。`organization_usage`が`require`または`allow`に設定されている場合にのみ適用されます。<br /><br />オプションには以下が含まれます。<ul><li>`no_prompt`：（デフォルト）プロンプトを表示しません。有効なOrganizationパラメーターのない要求は拒否されます。</li><li>`pre_login_prompt`：ログインする前に、Organizationの選択をユーザに求めます。このオプションは、`organization_usage`が`require`に設定されている場合にのみ有効です。</li><li>`post_login_prompt`：ユーザーに資格情報でログインするように促します。ログインした後で、Organizationの選択をユーザーに求めます。</li></ul>                                        |

### 応答ステータスコード

可能性のある応答ステータスコードは以下のとおりです。

| ステータスコード | エラーコード                    | メッセージ                                                                                                                                                                                 | 原因                                                |
| -------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- |
| `200`    |                           | Client successfully updated.（クライアントが正常に更新されました。）                                                                                                                                      |                                                   |
| `400`    | `invalid_uri`             | Invalid request URI.（要求URIが無効です。）メッセージは原因によって異なります。                                                                                                                                   | パスが有効ではありません。                                     |
| `400`    | `invalid_body`            | Invalid request body.（要求ボディーが無効です。）メッセージは原因によって異なります。                                                                                                                                 | 要求ペイロードが有効ではありません。                                |
| `401`    |                           | Invalid token.（無効なトークンです。）                                                                                                                                                            |                                                   |
| `401`    |                           | Client is not global.（クライアントがグローバルではありません。）                                                                                                                                           |                                                   |
| `401`    |                           | Invalid signature received for JSON Web Token validation.（JSON Web Tokenの検証に無効な署名を受け取りました。）                                                                                           |                                                   |
| `403`    | `insufficient_scope`      | Insufficient scope; expected any of: `update:clients`.（スコープが不足しています。`update:clients`が必要です。）                                                                                           | 渡されたベアラートークンのスコープでは許可されないフィールドの読み込みや書き出しが試行されました。 |
| `403`    | `insufficient_scope`      | Some fields cannot be updated with the permissions granted by the bearer token scopes.（一部のフィールドは、ベアラートークンのスコープで付加された権限では更新できません。）メッセージはフィールドやスコープによって異なります。                           | 渡されたベアラートークンのスコープでは許可されないフィールドの読み込みや書き出しが試行されました。 |
| `403`    | `operation_not_supported` | The account is not allowed to perform this operation.（アカウントには、この操作の実行が許可されていません。）                                                                                                     | アカウントにこの操作の実行が許可されていません。                          |
| `404`    | `inexistent_client`       | Client not found.（クライアントが見つかりません。）                                                                                                                                                    | 存在しないリソースです。指定されたアプリケーションは存在しません。                 |
| `429`    |                           | Too many requests.Check the X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset headers.（要求が多すぎます。X-RateLimit-Limit、X-RateLimit-Remaining、X-RateLimit-Resetヘッダーを確認してください。） |                                                   |
