Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Configurare attestazioni personalizzate per gli utenti
Questo documento spiega come configurare attestazioni personalizzate per gli utenti con
Identity Platform. Le attestazioni personalizzate vengono inserite nei token utente durante
l'autenticazione. La tua app può utilizzare questi claim per gestire scenari di autorizzazione complessi, ad esempio limitare l'accesso di un utente a una risorsa in base al suo ruolo.
Configurare le rivendicazioni personalizzate
Per preservare la sicurezza, imposta i claim personalizzati utilizzando l'SDK Admin sul tuo
server:
Imposta la rivendicazione personalizzata che vuoi utilizzare. Nell'esempio seguente, per l'utente viene impostato un
claim personalizzato per descrivere che è un amministratore:
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.}}
Per determinare quali attestazioni personalizzate sono presenti per un utente:
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"]);
Quando configuri i claim personalizzati, tieni presente quanto segue:
I claim personalizzati non possono avere una dimensione superiore a 1000 byte. Il tentativo di passare rivendicazioni superiori a 1000 byte genera un errore.
I claim personalizzati vengono inseriti nel JWT dell'utente al momento dell'emissione del token. I nuovi rivendicazioni non sono disponibili finché il token non viene aggiornato. Puoi aggiornare un token in silenzio chiamando user.getIdToken(true).
Per mantenere la continuità e la sicurezza, imposta i claim personalizzati solo in un ambiente di server sicuro.
Passaggi successivi
Scopri di più sulle funzioni di blocco, che possono essere utilizzate anche per impostare rivendicazioni personalizzate.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-09-04 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)."]]