ユーザーの画像を変更する
Auth0は、ユーザープロファイル内の共通プロファイルプロパティを正規化します。これには、name
やpicture
フィールドなどが含まれます。画像フィールドには、ソーシャルプロバイダーのプロフィール画像、またはユーザーのメールアドレスに関連付けられたGravatar画像のいずれかが入力されます。
デフォルトでは、すべてのデータベースユーザーにイニシャルの入ったプレースホルダー画像が設定されます。ユーザーの認証では、この画像フィールドはuser.picture
と呼ばれます。
Management APIを使用する
user.picture
属性がGoogle、Facebook、Xなど、Auth0以外のIDプロバイダーによって提供されている場合には直接編集できません。この属性を編集するには、ユーザープロファイルの作成時にのみIDプロバイダーからユーザー属性が更新されるように、Auth0との接続同期を構成する必要があります。詳細については、「ユーザープロファイルの更新にIDプロバイダー接続を構成する」をお読みください。そうすれば、ルート属性を個別に編集したり、Management APIを使用して一括インポートしたりできます。詳細については、「ユーザーを一括してインポートする」をお読みください。
または、メタデータを使用してユーザーの画像属性を保管することもできます。たとえば、アプリにプロフィール画像をアップロードする方法がある場合は、画像をアップロードすれば、user.user_metadata.picture
でURLを画像に設定できます。
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"}}'
Was this helpful?
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);
Was this helpful?
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))
}
Was this helpful?
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();
Was this helpful?
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);
});
Was this helpful?
#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];
Was this helpful?
$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;
}
Was this helpful?
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"))
Was this helpful?
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
Was this helpful?
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()
Was this helpful?
アクションを使用する
user_metadata
からの画像がIDトークンで返されるようにするには、event.user.user_metadata.picture
属性の存在を確認する新しいアクションを作成し、存在する場合はuser.picture
属性をその値に置き換える必要があります。そうすると、user_metadata
からの画像がIDトークンのpicture
クレームで返されます。
[Auth0 Dashboard]>[Actions(アクション)]>[Library(ライブラリー)]に移動して、[Build Custom(カスタムの構築)]を選択します。
アクションにわかりやすい名前(
Change user pictures
など)を入力し、[Login / Post Login
(ログイン/ログイン後)]のトリガー(アクションをログインフローに追加することになるため)を選択してから[Create(作成)]を選択します。Actionsコードエディターを見つけて、次のJavaScriptコードをコピーし、[Save Draft(下書きを保存)]を選択して変更を保存します。
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) } };
Was this helpful?
/Actionsコードエディターのサイドバーから、[Test(テスト)](再生アイコン)を選択してから、[Run(実行)]を選択し、コードをテストします。
アクションを稼働する準備ができたら、[Deploy(デプロイ)]を選択します。
最後に、作成したアクションをログインフローに追加します。フローにアクションをアタッチする方法については、「アクションを初めて作成する」の「アクションをフローにアタッチする」セクションをお読みください。
すべてのユーザーのデフォルト画像を変更する
プロフィール画像を設定していないすべてのユーザーのデフォルト画像を変更するには、アクションを使用できます。例:
exports.onExecutePostLogin = async (event, api) => {
const DEFAULT_PROFILE_IMAGE = '{yourDefaultImageUrl}';
api.idToken.setCustomClaim("picture", {defaultProfileImage});
};
Was this helpful?
このアクションでは、カスタム画像がIDトークンで返され、Googleなどの外部IDプロバイダーのログインから適用されるかもしれないpicture
プロパティを上書きします。
制限事項
Auth0データストアには制限があるため、アプリケーションのデータが制限を超えないようにするには、ユーザー画像の保管に外部データベースの使用をお勧めします。そうすることで、Auth0データストアを小さく保ち、より効率的な外部データベースを使用して追加データを保持できるようになります。詳細については、「ユーザーデータストレージ」をお読みください。