Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Configurer des revendications personnalisées sur les utilisateurs
Ce document explique comment configurer des revendications personnalisées sur les utilisateurs d'Identity Platform. Les revendications personnalisées sont insérées dans les jetons utilisateur lors de l'authentification. Votre application peut exploiter ces revendications pour gérer des scénarios d'autorisation complexes, tels que la restriction de l'accès d'un utilisateur à une ressource en fonction de son rôle.
Configurer des revendications personnalisées
Pour préserver la sécurité, définissez des revendications personnalisées à l'aide du SDK Admin sur votre serveur:
Définissez la revendication personnalisée que vous souhaitez utiliser. Dans l'exemple suivant, une revendication personnalisée est définie sur l'utilisateur pour indiquer qu'il est un administrateur :
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.}}
Pour déterminer quelles revendications personnalisées sont présentées à un utilisateur, procédez comme suit :
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"]);
Lorsque vous configurez des revendications personnalisées, tenez compte des points suivants:
La taille des revendications personnalisées ne peut pas dépasser 1 000 octets. Tenter de transmettre des revendications supérieures à 1 000 octets entraîne une erreur.
Les revendications personnalisées sont insérées dans le jeton JWT de l'utilisateur lors de l'émission du jeton. Les nouvelles revendications ne sont pas disponibles tant que le jeton n'est pas actualisé. Vous pouvez actualiser un jeton en mode silencieux en appelant user.getIdToken(true).
Pour assurer la continuité et la sécurité, ne définissez des revendications personnalisées que dans un environnement de serveur sécurisé.
Étape suivante
Découvrez les fonctions de blocage, qui peuvent également être utilisées pour définir des revendications personnalisées.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 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)."]]