> ## Documentation Index
> Fetch the complete documentation index at: https://docs-dev-fix-docs-5528-php-updates.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) + "*****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は、ユーザープロファイル内の共通プロファイルプロパティを正規化します。これには、`name`や`picture`フィールドなどが含まれます。画像フィールドには、ソーシャルプロバイダーのプロフィール画像、またはユーザーのメールアドレスに関連付けられたGravatar画像のいずれかが入力されます。

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

## Management APIを使用する

`user.picture`属性がGoogle、Facebook、Xなど、Auth0以外のIDプロバイダーによって提供されている場合には直接編集できません。この属性を編集するには、ユーザープロファイルの作成時にのみIDプロバイダーからユーザー属性が更新されるように、Auth0との接続同期を構成する必要があります。詳細については、「[ユーザープロファイルの更新にIDプロバイダー接続を構成する](/docs/ja-jp/manage-users/user-accounts/user-profiles/configure-connection-sync-with-auth0)」をお読みください。そうすれば、ルート属性を個別に編集したり、<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=management-api" tip="Management API: 顧客が管理タスクを実行できるようにするための製品。" cta="用語集の表示">Management API</Tooltip>を使用して一括インポートしたりできます。詳細については、「[ユーザーを一括してインポートする](/docs/ja-jp/manage-users/user-migration/bulk-user-imports)」をお読みください。

または、メタデータを使用してユーザーの画像属性を保管することもできます。たとえば、アプリにプロフィール画像をアップロードする方法がある場合は、画像をアップロードすれば、`user.user_metadata.picture`でURLを画像に設定できます。

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

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

  NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN",
                             @"content-type": @"application/json" };
  NSDictionary *parameters = @{ @"user_metadata": @{ @"picture": @"https://example.com/some-image.png" } };

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

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/users/USER_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/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
  ```

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

  let headers = [
    "authorization": "Bearer MGMT_API_ACCESS_TOKEN",
    "content-type": "application/json"
  ]
  let parameters = ["user_metadata": ["picture": "https://example.com/some-image.png"]] as [String : Any]

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

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

## アクションを使用する

`user_metadata`からの画像がIDトークンで返されるようにするには、`event.user.user_metadata.picture`属性の存在を確認する[新しいアクションを作成](/docs/ja-jp/customize/actions/write-your-first-action)し、存在する場合は`user.picture`属性をその値に置き換える必要があります。そうすると、`user_metadata`からの画像がIDトークンの`picture`クレームで返されます。

1. [［Auth0 Dashboard］>［Actions（アクション）］>［Library（ライブラリー）］](https://manage.auth0.com/#/actions/library)に移動して、**［Build Custom（カスタムの構築）］** を選択します。

2. アクションにわかりやすい**名前** （`Change user pictures`など）を入力し、［`Login / Post Login`（ログイン/ログイン後）］のトリガー（アクションをログインフローに追加することになるため）を選択してから\*\*［Create（作成）］\*\* を選択します。

3. Actionsコードエディターを見つけて、次のJavaScriptコードをコピーし、**［Save Draft（下書きを保存）］** を選択して変更を保存します。

   ```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コードエディターのサイドバーから、［Test（テスト）］（再生アイコン）を選択してから、**［Run（実行）］** を選択し、[コードをテスト](/docs/ja-jp/customize/actions/test-actions)します。

5. アクションを稼働する準備ができたら、**［Deploy（デプロイ）］** を選択します。

最後に、作成したアクションを[ログインフロー](https://manage.auth0.com/#/actions/flows/login/)に追加します。フローにアクションをアタッチする方法については、「[アクションを初めて作成する](/docs/ja-jp/customize/actions/write-your-first-action)」の「アクションをフローにアタッチする」セクションをお読みください。

## すべてのユーザーのデフォルト画像を変更する

プロフィール画像を設定していないすべてのユーザーのデフォルト画像を変更するには、アクションを使用できます。例：

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

このアクションでは、カスタム画像がIDトークンで返され、Googleなどの外部IDプロバイダーのログインから適用されるかもしれない`picture`プロパティを上書きします。

## 制限事項

Auth0データストアには制限があるため、アプリケーションのデータが制限を超えないようにするには、ユーザー画像の保管に外部データベースの使用をお勧めします。そうすることで、Auth0データストアを小さく保ち、より効率的な外部データベースを使用して追加データを保持できるようになります。詳細については、「[ユーザーデータストレージ](/docs/ja-jp/secure/security-guidance/data-security/user-data-storage)」をお読みください。

## もっと詳しく

* [ユーザープロファイルの構造](/docs/ja-jp/manage-users/user-accounts/user-profiles/user-profile-structure)
* [ユーザープロファイルのルート属性](/docs/ja-jp/manage-users/user-accounts/user-profiles/root-attributes)
* [ユーザープロファイルでのメタデータの使い方](/docs/ja-jp/manage-users/user-accounts/metadata)
* [Management APIを使ってメタデータを管理する](/docs/ja-jp/manage-users/user-accounts/metadata/manage-metadata-api)
* [ルールを使用してメタデータを管理](/docs/ja-jp/manage-users/user-accounts/metadata/manage-metadata-rules)
* [一括ユーザーインポート](/docs/ja-jp/manage-users/user-migration/bulk-user-imports)
