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

> ユーザーメタデータを使用してユーザーの picture フィールドを変更する方法と、すべてのユーザーに対するデフォルトの画像を変更する方法を説明します。

# ユーザー画像を変更する

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

Auth0 では、ユーザープロフィール内の一般的なプロファイル属性を正規化しています。これには、`name`、`picture` フィールドなどが含まれます。`picture` フィールドには、ソーシャルプロバイダーのプロフィール画像、またはユーザーのメールアドレスに関連付けられた Gravatar 画像が設定されます。

デフォルトでは、すべてのデータベースユーザーにイニシャル入りのプレースホルダー画像が設定されます。ユーザーを認証すると、この `picture` フィールドは `user.picture` として参照されます。

<div id="use-the-management-api">
  ## Management API を使用する
</div>

`user.picture` 属性は、Google、Facebook、X など、Auth0 以外の <Tooltip tip="IDプロバイダー（IdP）: デジタルアイデンティティを保存および管理するサービス。" cta="用語集を見る" href="/ja/docs/glossary?term=identity+providers">IDプロバイダー</Tooltip> によって提供される場合、直接編集することはできません。この属性を編集するには、ユーザー属性がユーザープロフィールの作成時にのみ IDプロバイダーから更新されるように、Auth0 との接続同期を設定する必要があります。詳しくは、[ユーザープロフィール更新のための IDプロバイダー接続の設定](/ja/docs/manage-users/user-accounts/user-profiles/configure-connection-sync-with-auth0) を参照してください。そうすると、ルート属性を個別に編集したり、<Tooltip tip="Management API: 顧客が管理タスクを実行できるようにする製品。" cta="用語集を見る" href="/ja/docs/glossary?term=Management+API">Management API</Tooltip> を使用して一括インポートで編集したりできるようになります。詳しくは、[ユーザーの一括インポート](/ja/docs/manage-users/user-migration/bulk-user-imports) を参照してください。

また、ユーザーの picture 属性を保存するために metadata を使用することもできます。たとえば、アプリでプロフィール画像をアップロードできる場合は、画像のアップロード後に、その URL を `user.user_metadata.picture` に設定できます。

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request PATCH \
    --url 'https://{yourDomain}/api/v2/users/USER_ID' \
    --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \
    --header 'content-type: application/json' \
    --data '{"user_metadata": {"picture": "https://example.com/some-image.png"}}'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID");
  var request = new RestRequest(Method.PATCH);
  request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN");
  request.AddHeader("content-type", "application/json");
  request.AddParameter("application/json", "{"user_metadata": {"picture": "https://example.com/some-image.png"}}", 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/users/USER_ID"

  	payload := strings.NewReader("{"user_metadata": {"picture": "https://example.com/some-image.png"}}")

  	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 theme={null}
  HttpResponse<String> response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID")
    .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN")
    .header("content-type", "application/json")
    .body("{"user_metadata": {"picture": "https://example.com/some-image.png"}}")
    .asString();
  ```

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

  var options = {
    method: 'PATCH',
    url: 'https://{yourDomain}/api/v2/users/USER_ID',
    headers: {
      authorization: 'Bearer MGMT_API_ACCESS_TOKEN',
      'content-type': 'application/json'
    },
    data: {user_metadata: {picture: 'https://example.com/some-image.png'}}
  };

  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/users/USER_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 => "{"user_metadata": {"picture": "https://example.com/some-image.png"}}",
    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 theme={null}
  import http.client

  conn = http.client.HTTPSConnection("")

  payload = "{"user_metadata": {"picture": "https://example.com/some-image.png"}}"

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

  conn.request("PATCH", "/{yourDomain}/api/v2/users/USER_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/users/USER_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["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN'
  request["content-type"] = 'application/json'
  request.body = "{"user_metadata": {"picture": "https://example.com/some-image.png"}}"

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

<div id="use-actions">
  ## Actions を使用する
</div>

`user_metadata` の画像が <Tooltip tip="クライアント自体を対象とした認証情報であり、リソースへのアクセスに使用するものではありません。" cta="用語集を表示" href="/ja/docs/glossary?term=ID+Token">IDトークン</Tooltip> に含まれて返されるようにするには、`event.user.user_metadata.picture` 属性が存在するかどうかを確認し、存在する場合は `user.picture` 属性をその値で置き換える [新しい Action を作成](/ja/docs/customize/actions/write-your-first-action) する必要があります。これにより、`user_metadata` の画像が IDトークンの `picture` クレームとして返されます。

1. [Auth0 Dashboard > Actions > Library](https://manage.auth0.com/#/actions/library) に移動し、**Build Custom** を選択します。

2. Action のわかりやすい **名前** (たとえば `Change user pictures`) を入力し、Action を Login フローに追加するために `Login / Post Login` トリガーを選択して、**Create** を選択します。

3. Actions Code Editor を開き、次の JavaScript コードをコピーして貼り付け、変更を保存するために **Save Draft** を選択します。

   ```js lines theme={null}
   exports.onExecutePostLogin = async (event, api) => {
     const { picture } = event.user.user_metadata;
     if (picture) {
       // Return the persisted user_metadata.picture in the ID token
       api.idToken.setCustomClaim("picture", picture)
     }
   };
   ```

4. Actions Code Editor のサイドバーで Test (再生アイコン) を選択し、**Run** を選択して [コードをテスト](/ja/docs/customize/actions/test-actions) します。

5. Action を本番で有効にする準備ができたら、**Deploy** を選択します。

最後に、作成した Action を [Login フロー](https://manage.auth0.com/#/actions/flows/login/) に追加します。Actions をフローにアタッチする方法については、[Write Your First Action](/ja/docs/customize/actions/write-your-first-action) の「Attach the Action to a flow」セクションを参照してください。

<div id="change-default-picture-for-all-users">
  ## すべてのユーザーのデフォルト画像を変更する
</div>

ユーザープロファイル画像を設定していないすべてのユーザーのデフォルト画像を変更するには、Action を使用できます。例:

```js lines theme={null}
exports.onExecutePostLogin = async (event, api) => {
  const DEFAULT_PROFILE_IMAGE = '{yourDefaultImageUrl}';
  api.idToken.setCustomClaim("picture", {defaultProfileImage});
};
```

この Action では、カスタム画像が IDトークンに含まれて返され、Google などの外部 IDプロバイダーによるログインから取得される可能性のある `picture` プロパティを上書きします。

<div id="limitations">
  ## 制限事項
</div>

Auth0 のデータストアには容量の制限があります。アプリケーションのデータがその上限を超えないように、ユーザー画像は外部データベースに保存することをお勧めします。これにより、Auth0 のデータストアを小さいまま維持しつつ、追加データはより効率的な外部データベースに保存できます。詳しくは、[ユーザーデータの保存](/ja/docs/secure/security-guidance/data-security/user-data-storage)を参照してください。

<div id="learn-more">
  ## 詳細情報
</div>

* [ユーザープロフィールの構造](/ja/docs/manage-users/user-accounts/user-profiles/user-profile-structure)
* [ユーザープロフィールのルート属性](/ja/docs/manage-users/user-accounts/user-profiles/root-attributes)
* [ユーザープロフィールにおけるメタデータの仕組み](/ja/docs/manage-users/user-accounts/metadata)
* [Management API を使用したメタデータの管理](/ja/docs/manage-users/user-accounts/metadata/manage-metadata-api)
* [Rules を使用したメタデータの管理](/ja/docs/manage-users/user-accounts/metadata/manage-metadata-rules)
* [ユーザーの一括インポート](/ja/docs/manage-users/user-migration/bulk-user-imports)
