Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Mengonfigurasi klaim kustom pada pengguna
Dokumen ini menjelaskan cara mengonfigurasi klaim kustom pada pengguna dengan Identity Platform. Klaim kustom disisipkan ke dalam token pengguna selama
autentikasi. Aplikasi Anda dapat menggunakan klaim ini untuk menangani skenario otorisasi
yang kompleks, seperti membatasi akses pengguna ke resource berdasarkan
perannya.
Menyiapkan klaim kustom
Untuk menjaga keamanan, tetapkan klaim kustom menggunakan Admin SDK di server Anda:
Tetapkan klaim kustom yang ingin Anda gunakan. Pada contoh berikut, klaim kustom ditetapkan pada pengguna untuk menjelaskan bahwa ia adalah administrator:
Node.js
// Set admin privilege on the user corresponding to uid.getAuth().setCustomUserClaims(uid,{admin:true}).then(()=>{// The new custom claims will propagate to the user's ID token the// next time a new one is issued.});
// Set admin privilege on the user corresponding to uid.Map<String,Object>claims=newHashMap<>();claims.put("admin",true);FirebaseAuth.getInstance().setCustomUserClaims(uid,claims);// The new custom claims will propagate to the user's ID token the// next time a new one is issued.
# Set admin privilege on the user corresponding to uid.auth.set_custom_user_claims(uid,{'admin':True})# The new custom claims will propagate to the user's ID token the# next time a new one is issued.
// Get an auth client from the firebase.Appclient,err:=app.Auth(ctx)iferr!=nil{log.Fatalf("error getting Auth client: %v\n",err)}// Set admin privilege on the user corresponding to uid.claims:=map[string]interface{}{"admin":true}err=client.SetCustomUserClaims(ctx,uid,claims)iferr!=nil{log.Fatalf("error setting custom claims %v\n",err)}// The new custom claims will propagate to the user's ID token the// next time a new one is issued.
// Set admin privileges on the user corresponding to uid.varclaims=newDictionary<string,object>(){{"admin",true},};awaitFirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(uid,claims);// The new custom claims will propagate to the user's ID token the// next time a new one is issued.
// Verify the ID token first.FirebaseTokendecoded=FirebaseAuth.getInstance().verifyIdToken(idToken);if(Boolean.TRUE.equals(decoded.getClaims().get("admin"))){// Allow access to requested admin resource.}
// Verify the ID token first.token,err:=client.VerifyIDToken(ctx,idToken)iferr!=nil{log.Fatal(err)}claims:=token.Claimsifadmin,ok:=claims["admin"];ok{ifadmin.(bool){//Allow access to requested admin resource.}}
// Verify the ID token first.FirebaseTokendecoded=awaitFirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken);objectisAdmin;if(decoded.Claims.TryGetValue("admin",outisAdmin)){if((bool)isAdmin){// Allow access to requested admin resource.}}
Untuk menentukan klaim kustom yang ada untuk pengguna:
Node.js
// Lookup the user associated with the specified uid.getAuth().getUser(uid).then((userRecord)=>{// The claims can be accessed on the user record.console.log(userRecord.customClaims['admin']);});
// Lookup the user associated with the specified uid.UserRecorduser=FirebaseAuth.getInstance().getUser(uid);System.out.println(user.getCustomClaims().get("admin"));
# Lookup the user associated with the specified uid.user=auth.get_user(uid)# The claims can be accessed on the user record.print(user.custom_claims.get('admin'))
// Lookup the user associated with the specified uid.user,err:=client.GetUser(ctx,uid)iferr!=nil{log.Fatal(err)}// The claims can be accessed on the user record.ifadmin,ok:=user.CustomClaims["admin"];ok{ifadmin.(bool){log.Println(admin)}}
// Lookup the user associated with the specified uid.UserRecorduser=awaitFirebaseAuth.DefaultInstance.GetUserAsync(uid);Console.WriteLine(user.CustomClaims["admin"]);
Saat menyiapkan klaim kustom, perhatikan hal-hal berikut:
Ukuran klaim kustom tidak boleh melebihi 1.000 byte. Mencoba meneruskan klaim
yang lebih besar dari 1.000 byte akan menyebabkan error.
Klaim kustom disisipkan ke dalam JWT pengguna saat token dikeluarkan. Klaim
baru tidak tersedia hingga token dimuat ulang. Anda dapat memuat ulang
token secara diam-diam dengan memanggil user.getIdToken(true).
Untuk mempertahankan kontinuitas dan keamanan, hanya tetapkan klaim kustom di lingkungan server yang aman.
Langkah selanjutnya
Pelajari lebih lanjut fungsi pemblokiran, yang juga dapat digunakan untuk menetapkan klaim kustom.
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Sulit dipahami","hardToUnderstand","thumb-down"],["Informasi atau kode contoh salah","incorrectInformationOrSampleCode","thumb-down"],["Informasi/contoh yang saya butuhkan tidak ada","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 2025-08-11 UTC."],[[["\u003cp\u003eCustom claims can be configured on users to manage complex authorization scenarios, such as restricting resource access based on user roles.\u003c/p\u003e\n"],["\u003cp\u003eCustom claims are set securely on the server using the Admin SDK, and the claims are inserted into the user's ID token during authentication.\u003c/p\u003e\n"],["\u003cp\u003eTo access and validate custom claims, the ID token needs to be verified first, then the claims within the token can be accessed.\u003c/p\u003e\n"],["\u003cp\u003eTo ensure security, setting custom claims should occur exclusively in a secure server environment, and they cannot exceed 1000 bytes.\u003c/p\u003e\n"],["\u003cp\u003eThe custom claims will not be available until the next time the token is refreshed.\u003c/p\u003e\n"]]],[],null,["Configure custom claims on users\n\nThis document explains how to configure custom claims on users with\nIdentity Platform. Custom claims are inserted into user tokens during\nauthentication. Your app can use these claims to handle complex authorization\nscenarios, such as restricting a user's access to a resource based on their\nrole.\n\nSet up custom claims\n\nTo preserve security, set custom claims using the Admin SDK on your\nserver:\n\n1. If you haven't already, [Install the Admin SDK](/identity-platform/docs/install-admin-sdk).\n\n2. Set the custom claim you want to use. In the following example, a custom\n claim is set on the user to describe that they're an administrator:\n\n Node.js \n\n ```javascript\n // Set admin privilege on the user corresponding to uid.\n\n getAuth()\n .setCustomUserClaims(uid, { admin: true })\n .then(() =\u003e {\n // The new custom claims will propagate to the user's ID token the\n // next time a new one is issued.\n });https://github.com/firebase/snippets-node/blob/f1869eeb97c2bbb713aff3deb5a67666da7bcb6b/auth/custom_claims.js#L13-L20\n ```\n\n Java \n\n ```java\n // Set admin privilege on the user corresponding to uid.\n Map\u003cString, Object\u003e claims = new HashMap\u003c\u003e();\n claims.put(\"admin\", true);\n FirebaseAuth.getInstance().setCustomUserClaims(uid, claims);\n // The new custom claims will propagate to the user's ID token the\n // next time a new one is issued. \n https://github.com/firebase/firebase-admin-java/blob/212ecea4bcccf4f6a9df42d21f70f66ebefe809b/src/test/java/com/google/firebase/snippets/FirebaseAuthSnippets.java#L157-L162\n ```\n\n Python \n\n ```python\n # Set admin privilege on the user corresponding to uid.\n auth.set_custom_user_claims(uid, {'admin': True})\n # The new custom claims will propagate to the user's ID token the\n # next time a new one is issued. \n https://github.com/firebase/firebase-admin-python/blob/5e752502fdaede3246e4224684dba6ea089a7726/snippets/auth/index.py#L282-L285\n ```\n\n Go \n\n ```go\n // Get an auth client from the firebase.App\n client, err := app.Auth(ctx)\n if err != nil {\n \tlog.Fatalf(\"error getting Auth client: %v\\n\", err)\n }\n\n // Set admin privilege on the user corresponding to uid.\n claims := map[string]interface{}{\"admin\": true}\n err = client.SetCustomUserClaims(ctx, uid, claims)\n if err != nil {\n \tlog.Fatalf(\"error setting custom claims %v\\n\", err)\n }\n // The new custom claims will propagate to the user's ID token the\n // next time a new one is issued. \n https://github.com/firebase/firebase-admin-go/blob/26dec0b7589ef7641eefd6681981024079b8524c/snippets/auth.go#L295-L308\n ```\n\n C# \n\n ```c#\n // Set admin privileges on the user corresponding to uid.\n var claims = new Dictionary\u003cstring, object\u003e()\n {\n { \"admin\", true },\n };\n await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(uid, claims);\n // The new custom claims will propagate to the user's ID token the\n // next time a new one is issued. \n https://github.com/firebase/firebase-admin-dotnet/blob/0901380f1e7d2bb0221d5954b20a9e053c6f889a/FirebaseAdmin/FirebaseAdmin.Snippets/FirebaseAuthSnippets.cs#L527-L534\n ```\n3. Validate the custom claim the next time it's sent to your server:\n\n Node.js \n\n ```javascript\n // Verify the ID token first.\n getAuth()\n .verifyIdToken(idToken)\n .then((claims) =\u003e {\n if (claims.admin === true) {\n // Allow access to requested admin resource.\n }\n });https://github.com/firebase/snippets-node/blob/f1869eeb97c2bbb713aff3deb5a67666da7bcb6b/auth/custom_claims.js#L24-L31\n ```\n\n Java \n\n ```java\n // Verify the ID token first.\n FirebaseToken decoded = FirebaseAuth.getInstance().verifyIdToken(idToken);\n if (Boolean.TRUE.equals(decoded.getClaims().get(\"admin\"))) {\n // Allow access to requested admin resource.\n }https://github.com/firebase/firebase-admin-java/blob/212ecea4bcccf4f6a9df42d21f70f66ebefe809b/src/test/java/com/google/firebase/snippets/FirebaseAuthSnippets.java#L167-L171\n ```\n\n Python \n\n ```python\n # Verify the ID token first.\n claims = auth.verify_id_token(id_token)\n if claims['admin'] is True:\n # Allow access to requested admin resource.\n pass \n https://github.com/firebase/firebase-admin-python/blob/5e752502fdaede3246e4224684dba6ea089a7726/snippets/auth/index.py#L290-L294\n ```\n\n Go \n\n ```go\n // Verify the ID token first.\n token, err := client.VerifyIDToken(ctx, idToken)\n if err != nil {\n \tlog.Fatal(err)\n }\n\n claims := token.Claims\n if admin, ok := claims[\"admin\"]; ok {\n \tif admin.(bool) {\n \t\t//Allow access to requested admin resource.\n \t}\n }https://github.com/firebase/firebase-admin-go/blob/26dec0b7589ef7641eefd6681981024079b8524c/snippets/auth.go#L316-L327\n ```\n\n C# \n\n ```c#\n // Verify the ID token first.\n FirebaseToken decoded = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken);\n object isAdmin;\n if (decoded.Claims.TryGetValue(\"admin\", out isAdmin))\n {\n if ((bool)isAdmin)\n {\n // Allow access to requested admin resource.\n }\n }\n https://github.com/firebase/firebase-admin-dotnet/blob/0901380f1e7d2bb0221d5954b20a9e053c6f889a/FirebaseAdmin/FirebaseAdmin.Snippets/FirebaseAuthSnippets.cs#L539-L549\n ```\n4. To determine what custom claims are present for a user:\n\n Node.js \n\n ```javascript\n // Lookup the user associated with the specified uid.\n getAuth()\n .getUser(uid)\n .then((userRecord) =\u003e {\n // The claims can be accessed on the user record.\n console.log(userRecord.customClaims['admin']);\n });https://github.com/firebase/snippets-node/blob/f1869eeb97c2bbb713aff3deb5a67666da7bcb6b/auth/custom_claims.js#L35-L41\n ```\n\n Java \n\n ```java\n // Lookup the user associated with the specified uid.\n UserRecord user = FirebaseAuth.getInstance().getUser(uid);\n System.out.println(user.getCustomClaims().get(\"admin\"));https://github.com/firebase/firebase-admin-java/blob/212ecea4bcccf4f6a9df42d21f70f66ebefe809b/src/test/java/com/google/firebase/snippets/FirebaseAuthSnippets.java#L175-L177\n ```\n\n Python \n\n ```python\n # Lookup the user associated with the specified uid.\n user = auth.get_user(uid)\n # The claims can be accessed on the user record.\n print(user.custom_claims.get('admin'))https://github.com/firebase/firebase-admin-python/blob/5e752502fdaede3246e4224684dba6ea089a7726/snippets/auth/index.py#L298-L301\n ```\n\n Go \n\n ```go\n // Lookup the user associated with the specified uid.\n user, err := client.GetUser(ctx, uid)\n if err != nil {\n \tlog.Fatal(err)\n }\n // The claims can be accessed on the user record.\n if admin, ok := user.CustomClaims[\"admin\"]; ok {\n \tif admin.(bool) {\n \t\tlog.Println(admin)\n \t}\n }https://github.com/firebase/firebase-admin-go/blob/26dec0b7589ef7641eefd6681981024079b8524c/snippets/auth.go#L334-L344\n ```\n\n C# \n\n ```c#\n // Lookup the user associated with the specified uid.\n UserRecord user = await FirebaseAuth.DefaultInstance.GetUserAsync(uid);\n Console.WriteLine(user.CustomClaims[\"admin\"]);https://github.com/firebase/firebase-admin-dotnet/blob/0901380f1e7d2bb0221d5954b20a9e053c6f889a/FirebaseAdmin/FirebaseAdmin.Snippets/FirebaseAuthSnippets.cs#L553-L555\n ```\n\nWhen setting up custom claims, keep the following in mind:\n\n- Custom claims cannot exceed 1000 bytes in size. Attempting to pass claims larger than 1000 bytes results in an error.\n- Custom claims are inserted into the user JWT when the token is issued. New claims are not available until the token is refreshed. You can refresh a token silently by calling `user.getIdToken(true)`.\n- To maintain continuity and security, only set custom claims in a secure server environment.\n\nWhat's next\n\n- Learn more about [blocking functions](/identity-platform/docs/blocking-functions), which can also be used to set custom claims.\n- Learn more about Identity Platform custom claims in the [Admin SDK reference documentation](https://firebase.google.com/docs/auth/admin/custom-claims)."]]