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

# ユーザーの同意とサードパーティアプリケーション

> APIを、それを使用するアプリケーションから切り離す方法と、自分で制御していない、信頼できないサードパーティアプリの定義について説明します。

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()) {
              processedNode = processedNode.replace(new RegExp(key, "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 [processedChildren, setProcessedChildren] = useState(children);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      unsubscribe = window.autorun(() => {
        let processedChildren = children;
        for (const [key, value] of window.rootStore.variableStore.values.entries()) {
          processedChildren = processedChildren.replace(new RegExp(key, "g"), value);
        }
        setProcessedChildren(processedChildren);
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  return <CodeBlock filename={filename} icon={icon} language={language} lines highlight={highlight}>
      {processedChildren}
    </CodeBlock>;
};

[OIDC](/docs/ja-JP/ja-jp/authenticate/protocols/openid-connect-protocol)準拠の認証パイプラインでは、リソースサーバー（APIなど）をアプリケーションとは別のエンティティとして定義することができます。そうすることで、APIを使用するアプリケーションからAPIを切り離すだけでなく、[サードパーティアプリケーション](/docs/ja-JP/ja-jp/get-started/applications/confidential-and-public-applications/first-party-and-third-party-applications)を定義して、外部パーティに対し、APIの内部で保護されているリソースへの安全なアクセスを許可することができます。

<div id="consent-dialog">
  ## 同意ダイアログ
</div>

ユーザーがサードパーティアプリケーションを通じて認証を行い、そのアプリケーションがユーザー情報へのアクセスや、代理としてAPIで何らかのアクションを行うことへの認可を求める場合、ユーザーに対して同意ダイアログが表示されます。

たとえば、このような要求：

```lines theme={null}
GET /authorize?
client_id=some_third_party_client
&redirect_uri=https://fabrikam.com/contoso_social
&response_type=token id_token
&__scope=openid profile email read:posts write:posts__
&__audience=https://social.contoso.com__
&nonce=...
&state=...
```

は、次のようなユーザー同意ダイアログになります。

<Frame>
  <img src="https://mintcdn.com/generaltranslationinc/xDgF_gm8-0tTk54s/docs/images/ja-jp/cdy7uua7fh8z/5Cz3aZKw8RRVlMkc5Zl6x7/3cbb542cc383a812a1116cd5ee04a7de/Consent_prompt.png?fit=max&auto=format&n=xDgF_gm8-0tTk54s&q=85&s=312222c31376e1c031a429332b856e3f" alt="認可 - ユーザーの同意とアプリケーション - 同意ダイアログ" width="402" height="578" data-path="docs/images/ja-jp/cdy7uua7fh8z/5Cz3aZKw8RRVlMkc5Zl6x7/3cbb542cc383a812a1116cd5ee04a7de/Consent_prompt.png" />
</Frame>

ユーザーがアプリケーションの要求を承認すると、ユーザー権限付与が作成されます。付与は、このアプリケーション、このリソースサーバー、このスコープの組み合わせに対するユーザーの同意を表します。アプリケーションは、その後、通常どおりにAuth0から認証成功の応答を受け取ります。

一度同意が与えられると、その同意が明示的に取り消されるまで、ログイン時に同意ダイアログが表示されなくなります。

<div id="scope-descriptions">
  ## スコープの説明
</div>

デフォルトでは、同意ページは、スコープの名前を使ってユーザーの同意を求めます。下の図のように、スコープ名を **action:resource\_name** 形式で定義します。

<Frame>
  <img src="https://mintcdn.com/generaltranslationinc/JoMgZsgQxj2_Gov3/docs/images/ja-jp/cdy7uua7fh8z/3Z4Ofbj5yF7eg5cLfcauh9/304828f6a825bb01c5aeb3a7c8d1915f/Blog_API_Permissions.png?fit=max&auto=format&n=JoMgZsgQxj2_Gov3&q=85&s=44849e050795b6298d47b83ea0674243" alt="認可 - ユーザーの同意とアプリケーション - 同意スコープ" width="1002" height="684" data-path="docs/images/ja-jp/cdy7uua7fh8z/3Z4Ofbj5yF7eg5cLfcauh9/304828f6a825bb01c5aeb3a7c8d1915f/Blog_API_Permissions.png" />
</Frame>

同意ページは、同じリソースに対するスコープをグループにまとめ、そのリソースに対するアクションを1行に表示します。たとえば上記の構成では、 **Posts: read and write your posts（投稿：あなたの投稿の読み取りと書き出し）** と表示されます。

代わりに **［Description（説明）］** フィールドを表示したい場合は、テナントの **use\_scope\_descriptions\_for\_consent** を **true** に設定します。これは、そのテナント上のすべてのAPIの同意プロンプトに影響します。

**use\_scope\_descriptions\_for\_consent** フラグを設定するには、APIに適切な呼び出しをする必要があります。

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request PATCH \
    --url 'https://{yourDomain}/api/v2/tenants/settings' \
    --header 'authorization: Bearer API2_ACCESS_TOKEN' \
    --header 'cache-control: no-cache' \
    --header 'content-type: application/json' \
    --data '{ "flags": { "use_scope_descriptions_for_consent": true } }'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings");
  var request = new RestRequest(Method.PATCH);
  request.AddHeader("content-type", "application/json");
  request.AddHeader("authorization", "Bearer API2_ACCESS_TOKEN");
  request.AddHeader("cache-control", "no-cache");
  request.AddParameter("application/json", "{ "flags": { "use_scope_descriptions_for_consent": true } }", 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("{ "flags": { "use_scope_descriptions_for_consent": true } }")

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

  	req.Header.Add("content-type", "application/json")
  	req.Header.Add("authorization", "Bearer API2_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 response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings")
    .header("content-type", "application/json")
    .header("authorization", "Bearer API2_ACCESS_TOKEN")
    .header("cache-control", "no-cache")
    .body("{ "flags": { "use_scope_descriptions_for_consent": true } }")
    .asString();
  ```

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

  var options = {
    method: 'PATCH',
    url: 'https://{yourDomain}/api/v2/tenants/settings',
    headers: {
      'content-type': 'application/json',
      authorization: 'Bearer API2_ACCESS_TOKEN',
      'cache-control': 'no-cache'
    },
    data: {flags: {use_scope_descriptions_for_consent: true}}
  };

  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 API2_ACCESS_TOKEN",
                             @"cache-control": @"no-cache" };
  NSDictionary *parameters = @{ @"flags": @{ @"use_scope_descriptions_for_consent": @YES } };

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

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/tenants/settings"]
                                                         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/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 => "{ "flags": { "use_scope_descriptions_for_consent": true } }",
    CURLOPT_HTTPHEADER => [
      "authorization: Bearer API2_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 = "{ "flags": { "use_scope_descriptions_for_consent": true } }"

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

  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["content-type"] = 'application/json'
  request["authorization"] = 'Bearer API2_ACCESS_TOKEN'
  request["cache-control"] = 'no-cache'
  request.body = "{ "flags": { "use_scope_descriptions_for_consent": true } }"

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

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

  let headers = [
    "content-type": "application/json",
    "authorization": "Bearer API2_ACCESS_TOKEN",
    "cache-control": "no-cache"
  ]
  let parameters = ["flags": ["use_scope_descriptions_for_consent": true]] as [String : Any]

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

  let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/api/v2/tenants/settings")! 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>

<div id="handle-rejected-permissions">
  ## 拒否された許可に対処する
</div>

ユーザーがアプリケーションへの同意を拒否した場合は、要求の中で指定された`redirect_uri`に、`access_denied`エラーと共にリダイレクトされます。

```lines theme={null}
HTTP/1.1 302 Found
Location: https://fabrikam.com/contoso_social#
    error=access_denied
    &state=...
```

<div id="skip-consent-for-first-party-applications">
  ## ファーストパーティアプリケーションに対して同意をスキップする
</div>

ファーストパーティアプリケーションは、同意ダイアログをスキップできますが、これはユーザーの代わりにアクセスしようとしているAPIの **［Allow Skipping User Consent（ユーザー同意のスキップの許可）］** オプションが有効になっている場合にのみ可能です。

<Card title="ユーザーの同意とアプリケーション">
  現時点では、検証可能なファーストパーティアプリケーションのみが同意ダイアログをスキップできます。`localhost`は検証可能なファーストパーティーになり得ない（ユーザーが悪意のあるアプリケーションを`localhost`で実行する可能性がある）ため、ファーストパーティーアプリケーションであるかにかかわらず、`localhost`で実行されるアプリケーションには常に同意ダイアログが表示されます。開発中には、以下のようなエントリーを`/etc/hosts`ファイルに追加すると、これを回避することができます。

  `127.0.0.1 myapp.example`

  同様に、「`localhost`」がアプリケーションの **Allowed Callback URLs（許可されているコールバックURL）** 設定（[［Dashboard］>［Applications（アプリケーション）］>［Settings（設定）］](https://manage.auth0.com/#/applications/\{yourClientId}/settings)）にあるいずれかのドメインに含まれている場合、（ファーストパーティーアプリケーションであっても）同意はスキップできません。必ず、 **Allowed Callback URLs（許可されているコールバックURL）** を更新して、アプリケーションに構成したコールバックURLと更新後のドメインマッピングが一致するようにしてください。
</Card>

サードパーティアプリケーションは信頼できないものとみなされるため、同意ダイアログをスキップできません。

ユーザーが、一度同意したものの、それを取り消したい場合は：

<div id="revoke-consent">
  ## 同意を取り消す
</div>

[リソース所有者のパスワードフロー](/docs/ja-JP/ja-jp/get-started/authentication-and-authorization-flow/resource-owner-password-flow)を使うときは、同意ダイアログは使用されません。ユーザーが直接アプリケーションにパスワードを入力し、これがアプリケーションに対してユーザーアカウントへのフルアクセスを付与したことと同じになるためです。

1. [［Auth0 Dashboard］>［User Management（ユーザー管理］>［Users（ユーザー）］](https://manage.auth0.com/#/users)に移動し、同意を取り消すユーザーをクリックします。
2. **［Authorized Application（認可アプリケーション）］** タブをクリックします。
3. 該当するアプリケーションの横にある **［Revoke（取り消し）］** をクリックします。

<div id="password-based-flows">
  ## パスワードベースのフロー
</div>

`/authorize`エンドポイントにリダイレクトするときに`prompt=consent`パラメーターを含めることで、ユーザーに対して同意を強制できます。これは、ユーザーにアプリケーションと要求されたスコープに対するユーザー付与がすでにある場合でも同じです。

<div id="force-users-to-provide-consent">
  ## ユーザーに同意を強制する
</div>

同意ダイアログのUIは、カスタマイズすることも、カスタムドメインに設定することもできません。

<div id="learn-more">
  ## もっと詳しく
</div>

* [ファーストパーティーアプリケーションとサードパーティーアプリケーション](/docs/ja-JP/ja-jp/get-started/applications/confidential-and-public-applications/first-party-and-third-party-applications)
* [アプリケーションの所有権を表示する](/docs/ja-JP/ja-jp/get-started/applications/confidential-and-public-applications/view-application-ownership)
* [機密アプリケーションと公開アプリケーション](/docs/ja-JP/ja-jp/get-started/applications/confidential-and-public-applications)
* [サードパーティアプリケーションを有効にする](/docs/ja-JP/ja-jp/get-started/applications/confidential-and-public-applications/enable-third-party-applications)
* [アプリケーションの付与タイプ](/docs/ja-JP/ja-jp/get-started/applications/application-grant-types)
