Configura attestazioni personalizzate per gli utenti
Questo documento spiega come configurare attestazioni personalizzate per gli utenti con e Identity Platform. Le rivendicazioni personalizzate vengono inserite nei token utente autenticazione. La tua app può usare queste dichiarazioni per gestire autorizzazioni complesse come la limitazione dell'accesso di un utente a una risorsa in base ruolo.
Configura rivendicazioni personalizzate
Per preservare la sicurezza, imposta rivendicazioni personalizzate utilizzando l'SDK Admin sul tuo server:
Se non l'hai ancora fatto, installa SDK Admin.
Imposta la rivendicazione personalizzata che vuoi utilizzare. Nell'esempio seguente, viene impostata sull'utente per indicare di essere 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. });
Java
// Set admin privilege on the user corresponding to uid. Map<String, Object> claims = new HashMap<>(); 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.
Python
# 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.
Vai
// Get an auth client from the firebase.App client, err := app.Auth(ctx) if err != 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) if err != 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.
C#
// Set admin privileges on the user corresponding to uid. var claims = new Dictionary<string, object>() { { "admin", true }, }; await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(uid, claims); // The new custom claims will propagate to the user's ID token the // next time a new one is issued.
Convalida la rivendicazione personalizzata la prossima volta che viene inviata al tuo server:
Node.js
// Verify the ID token first. getAuth() .verifyIdToken(idToken) .then((claims) => { if (claims.admin === true) { // Allow access to requested admin resource. } });
Java
// Verify the ID token first. FirebaseToken decoded = FirebaseAuth.getInstance().verifyIdToken(idToken); if (Boolean.TRUE.equals(decoded.getClaims().get("admin"))) { // Allow access to requested admin resource. }
Python
# Verify the ID token first. claims = auth.verify_id_token(id_token) if claims['admin'] is True: # Allow access to requested admin resource. pass
Vai
// Verify the ID token first. token, err := client.VerifyIDToken(ctx, idToken) if err != nil { log.Fatal(err) } claims := token.Claims if admin, ok := claims["admin"]; ok { if admin.(bool) { //Allow access to requested admin resource. } }
C#
// Verify the ID token first. FirebaseToken decoded = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken); object isAdmin; if (decoded.Claims.TryGetValue("admin", out isAdmin)) { if ((bool)isAdmin) { // Allow access to requested admin resource. } }
Per determinare quali rivendicazioni 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']); });
Java
// Lookup the user associated with the specified uid. UserRecord user = FirebaseAuth.getInstance().getUser(uid); System.out.println(user.getCustomClaims().get("admin"));
Python
# 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'))
Vai
// Lookup the user associated with the specified uid. user, err := client.GetUser(ctx, uid) if err != nil { log.Fatal(err) } // The claims can be accessed on the user record. if admin, ok := user.CustomClaims["admin"]; ok { if admin.(bool) { log.Println(admin) } }
C#
// Lookup the user associated with the specified uid. UserRecord user = await FirebaseAuth.DefaultInstance.GetUserAsync(uid); Console.WriteLine(user.CustomClaims["admin"]);
Quando configuri le rivendicazioni personalizzate, tieni presente quanto segue:
- Le rivendicazioni personalizzate non possono superare i 1000 byte. Tentativo di passare le rivendicazioni Se superano i 1000 byte, viene generato un errore.
- Le rivendicazioni personalizzate vengono inserite nel JWT dell'utente quando viene emesso il token. Nuovi
le attestazioni non sono disponibili finché il token non viene aggiornato. Puoi aggiornare
automaticamente un token chiamando
user.getIdToken(true)
. - Per garantire continuità e sicurezza, imposta le attestazioni personalizzate solo in un ambiente sicuro dell'ambiente server.
Passaggi successivi
- Scopri di più sulle funzioni di blocco, che possono essere utilizzate anche per impostare rivendicazioni personalizzate.
- Scopri di più sulle attestazioni personalizzate di Identity Platform nel Documentazione di riferimento per SDK Admin.