Controllo dell'accesso con rivendicazioni personalizzate e regole di sicurezza

L'SDK Firebase Admin supporta la definizione di attributi personalizzati sugli account utente. Ciò consente di implementare varie strategie di controllo degli accessi, incluso il controllo degli accessi basato sui ruoli, nelle app Firebase. Questi attributi personalizzati possono concedere agli utenti diversi livelli di accesso (ruoli), che vengono applicati nelle regole di sicurezza di un'applicazione.

I ruoli utente possono essere definiti per i seguenti casi comuni:

  • Concedere a un utente privilegi amministrativi per accedere a dati e risorse.
  • Definizione di diversi gruppi a cui appartiene un utente.
  • Fornire l'accesso a più livelli:
    • Differenziazione degli abbonati a pagamento/senza abbonamento.
    • Differenziare i moderatori dagli utenti regolari.
    • Domanda di insegnante/studente e così via.
  • Aggiungi un identificatore aggiuntivo a un utente. Ad esempio, un utente Firebase potrebbe essere mappato a un UID diverso in un altro sistema.

Consideriamo un caso in cui vuoi limitare l'accesso al nodo del database "adminContent". Puoi farlo con una ricerca nel database di un elenco di utenti amministratori. Tuttavia, puoi raggiungere lo stesso obiettivo in modo più efficiente utilizzando un'attestazione utente personalizzata denominata admin con la seguente regola Realtime Database:

{
  "rules": {
    "adminContent": {
      ".read": "auth.token.admin === true",
      ".write": "auth.token.admin === true",
    }
  }
}

Le rivendicazioni utente personalizzate sono accessibili tramite i token di autenticazione dell'utente. Nell'esempio precedente, solo gli utenti con admin impostato su true nella rivendicazione del token avrebbero accesso in lettura/scrittura al nodo adminContent. Poiché il token ID contiene già queste asserzioni, non è necessaria alcuna elaborazione o ricerca aggiuntiva per verificare le autorizzazioni amministrative. Inoltre, il token ID è un meccanismo attendibile per la distribuzione di queste rivendicazioni personalizzate. Tutto l'accesso autenticato deve convalidare il token ID prima di elaborare la richiesta associata.

Gli esempi di codice e le soluzioni descritti in questa pagina si basano sia sulle API Firebase Auth lato client sia sulle API Auth lato server fornite dall'SDK Admin.

Impostare e convalidare attestazioni utente personalizzate tramite l'SDK Admin

Le rivendicazioni personalizzate possono contenere dati sensibili, pertanto devono essere impostate solo da un ambiente server privilegiato tramite l'SDK Firebase Admin.

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.

L'oggetto delle rivendicazioni personalizzate non deve contenere nomi di chiavi riservati OIDC o nomi riservati di Firebase. Il payload delle rivendicazioni personalizzate non deve superare i 1000 byte.

Un token ID inviato a un server di backend può confermare l'identità e il livello di accesso dell'utente utilizzando l'SDK Admin nel seguente modo:

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.
    }
}

Puoi anche controllare le rivendicazioni personalizzate esistenti di un utente, disponibili come proprietà dell'oggetto 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"]);

Puoi eliminare le rivendicazioni personalizzate di un utente passando null per customClaims.

Propagare attestazioni personalizzate al client

Dopo che le nuove rivendicazioni vengono modificate per un utente tramite l'SDK Admin, vengono propagate a un utente autenticato sul lato client tramite il token ID nei seguenti modi:

  • Un utente accede o esegue di nuovo l'autenticazione dopo la modifica delle rivendicazioni personalizzate. Il token ID emesso di conseguenza conterrà le rivendicazioni più recenti.
  • L'ID token di una sessione utente esistente viene aggiornato dopo la scadenza di un token precedente.
  • Un token ID viene aggiornato forzatamente chiamando currentUser.getIdToken(true).

Accedere alle attestazioni personalizzate sul client

Le rivendicazioni personalizzate possono essere recuperate solo tramite il token ID dell'utente. L'accesso a queste rivendicazioni potrebbe essere necessario per modificare l'interfaccia utente del client in base al ruolo o al livello di accesso dell'utente. Tuttavia, l'accesso al backend deve essere sempre applicato tramite il token ID dopo la convalida e l'analisi delle relative rivendicazioni. Le rivendicazioni personalizzate non devono essere inviate direttamente al backend, in quanto non possono essere considerate attendibili al di fuori del token.

Una volta che le ultime rivendicazioni sono state propagate al token ID di un utente, puoi ottenerle recuperando il token ID:

JavaScript

firebase.auth().currentUser.getIdTokenResult()
  .then((idTokenResult) => {
     // Confirm the user is an Admin.
     if (!!idTokenResult.claims.admin) {
       // Show admin UI.
       showAdminUI();
     } else {
       // Show regular user UI.
       showRegularUI();
     }
  })
  .catch((error) => {
    console.log(error);
  });

Android

user.getIdToken(false).addOnSuccessListener(new OnSuccessListener<GetTokenResult>() {
  @Override
  public void onSuccess(GetTokenResult result) {
    boolean isAdmin = result.getClaims().get("admin");
    if (isAdmin) {
      // Show admin UI.
      showAdminUI();
    } else {
      // Show regular user UI.
      showRegularUI();
    }
  }
});

Swift

user.getIDTokenResult(completion: { (result, error) in
  guard let admin = result?.claims?["admin"] as? NSNumber else {
    // Show regular user UI.
    showRegularUI()
    return
  }
  if admin.boolValue {
    // Show admin UI.
    showAdminUI()
  } else {
    // Show regular user UI.
    showRegularUI()
  }
})

Objective-C

user.getIDTokenResultWithCompletion:^(FIRAuthTokenResult *result,
                                      NSError *error) {
  if (error != nil) {
    BOOL *admin = [result.claims[@"admin"] boolValue];
    if (admin) {
      // Show admin UI.
      [self showAdminUI];
    } else {
      // Show regular user UI.
      [self showRegularUI];
    }
  }
}];

Best practice per le rivendicazioni personalizzate

Le rivendicazioni personalizzate vengono utilizzate solo per fornire il controllo dell'accesso. Non sono progettati per memorizzare dati aggiuntivi (come il profilo e altri dati personalizzati). Sebbene possa sembrare un meccanismo conveniente per farlo, è fortemente sconsigliato in quanto queste rivendicazioni vengono archiviate nel token ID e potrebbero causare problemi di prestazioni perché tutte le richieste autenticate contengono sempre un token ID Firebase corrispondente all'utente che ha eseguito l'accesso.

  • Utilizza le rivendicazioni personalizzate per archiviare i dati solo per controllare l'accesso degli utenti. Tutti gli altri dati devono essere archiviati separatamente tramite il database in tempo reale o un altro spazio di archiviazione lato server.
  • Le rivendicazioni personalizzate hanno dimensioni limitate. Il passaggio di un payload di rivendicazioni personalizzate superiore a 1000 byte genererà un errore.

Esempi e casi d'uso

Gli esempi riportati di seguito illustrano le rivendicazioni personalizzate nel contesto di casi d'uso specifici di Firebase.

Definizione dei ruoli tramite Firebase Functions al momento della creazione dell'utente

In questo esempio, le attestazioni personalizzate vengono impostate su un utente al momento della creazione utilizzando Cloud Functions.

È possibile aggiungere rivendicazioni personalizzate utilizzando Cloud Functions e propagarle immediatamente con Realtime Database. La funzione viene chiamata solo al momento della registrazione utilizzando un attivatore onCreate. Una volta impostate, le rivendicazioni personalizzate vengono propagate a tutte le sessioni esistenti e future. La volta successiva che l'utente accede con le credenziali utente, il token contiene le rivendicazioni personalizzate.

Implementazione lato client (JavaScript)

const provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider)
.catch(error => {
  console.log(error);
});

let callback = null;
let metadataRef = null;
firebase.auth().onAuthStateChanged(user => {
  // Remove previous listener.
  if (callback) {
    metadataRef.off('value', callback);
  }
  // On user login add new listener.
  if (user) {
    // Check if refresh is required.
    metadataRef = firebase.database().ref('metadata/' + user.uid + '/refreshTime');
    callback = (snapshot) => {
      // Force refresh to pick up the latest custom claims changes.
      // Note this is always triggered on first call. Further optimization could be
      // added to avoid the initial trigger when the token is issued and already contains
      // the latest claims.
      user.getIdToken(true);
    };
    // Subscribe new listener to changes on that node.
    metadataRef.on('value', callback);
  }
});

Cloud Functions logic

Viene aggiunto un nuovo nodo del database (metadata/($uid)} con accesso in lettura/scrittura limitato all'utente autenticato.

const functions = require('firebase-functions');
const { initializeApp } = require('firebase-admin/app');
const { getAuth } = require('firebase-admin/auth');
const { getDatabase } = require('firebase-admin/database');

initializeApp();

// On sign up.
exports.processSignUp = functions.auth.user().onCreate(async (user) => {
  // Check if user meets role criteria.
  if (
    user.email &&
    user.email.endsWith('@admin.example.com') &&
    user.emailVerified
  ) {
    const customClaims = {
      admin: true,
      accessLevel: 9
    };

    try {
      // Set custom user claims on this newly created user.
      await getAuth().setCustomUserClaims(user.uid, customClaims);

      // Update real-time database to notify client to force refresh.
      const metadataRef = getDatabase().ref('metadata/' + user.uid);

      // Set the refresh time to the current UTC timestamp.
      // This will be captured on the client to force a token refresh.
      await  metadataRef.set({refreshTime: new Date().getTime()});
    } catch (error) {
      console.log(error);
    }
  }
});

Regole del database

{
  "rules": {
    "metadata": {
      "$user_id": {
        // Read access only granted to the authenticated user.
        ".read": "$user_id === auth.uid",
        // Write access only via Admin SDK.
        ".write": false
      }
    }
  }
}

Definizione dei ruoli tramite una richiesta HTTP

L'esempio seguente imposta attestazioni utente personalizzate per un utente che ha appena eseguito l'accesso tramite una richiesta HTTP.

Implementazione lato client (JavaScript)

const provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider)
.then((result) => {
  // User is signed in. Get the ID token.
  return result.user.getIdToken();
})
.then((idToken) => {
  // Pass the ID token to the server.
  $.post(
    '/setCustomClaims',
    {
      idToken: idToken
    },
    (data, status) => {
      // This is not required. You could just wait until the token is expired
      // and it proactively refreshes.
      if (status == 'success' && data) {
        const json = JSON.parse(data);
        if (json && json.status == 'success') {
          // Force token refresh. The token claims will contain the additional claims.
          firebase.auth().currentUser.getIdToken(true);
        }
      }
    });
}).catch((error) => {
  console.log(error);
});

Implementazione del backend (SDK Admin)

app.post('/setCustomClaims', async (req, res) => {
  // Get the ID token passed.
  const idToken = req.body.idToken;

  // Verify the ID token and decode its payload.
  const claims = await getAuth().verifyIdToken(idToken);

  // Verify user is eligible for additional privileges.
  if (
    typeof claims.email !== 'undefined' &&
    typeof claims.email_verified !== 'undefined' &&
    claims.email_verified &&
    claims.email.endsWith('@admin.example.com')
  ) {
    // Add custom claims for additional privileges.
    await getAuth().setCustomUserClaims(claims.sub, {
      admin: true
    });

    // Tell client to refresh token on user.
    res.end(JSON.stringify({
      status: 'success'
    }));
  } else {
    // Return nothing.
    res.end(JSON.stringify({ status: 'ineligible' }));
  }
});

Lo stesso flusso può essere utilizzato per l'upgrade del livello di accesso di un utente esistente. Prendiamo ad esempio un utente senza costi che esegue l'upgrade a un abbonamento a pagamento. Il token ID dell'utente viene inviato con i dati di pagamento al server di backend tramite una richiesta HTTP. Una volta elaborato correttamente il pagamento, l'utente viene impostato come abbonato a pagamento tramite l'Admin SDK. Al client viene restituita una risposta HTTP riuscita per forzare l'aggiornamento del token.

Definizione dei ruoli tramite script di backend

Uno script ricorrente (non avviato dal client) potrebbe essere impostato per l'esecuzione per aggiornare le rivendicazioni personalizzate dell'utente:

Node.js

getAuth()
  .getUserByEmail('user@admin.example.com')
  .then((user) => {
    // Confirm user is verified.
    if (user.emailVerified) {
      // Add custom claims for additional privileges.
      // This will be picked up by the user on token refresh or next sign in on new device.
      return getAuth().setCustomUserClaims(user.uid, {
        admin: true,
      });
    }
  })
  .catch((error) => {
    console.log(error);
  });

Java

UserRecord user = FirebaseAuth.getInstance()
    .getUserByEmail("user@admin.example.com");
// Confirm user is verified.
if (user.isEmailVerified()) {
  Map<String, Object> claims = new HashMap<>();
  claims.put("admin", true);
  FirebaseAuth.getInstance().setCustomUserClaims(user.getUid(), claims);
}

Python

user = auth.get_user_by_email('user@admin.example.com')
# Confirm user is verified
if user.email_verified:
    # Add custom claims for additional privileges.
    # This will be picked up by the user on token refresh or next sign in on new device.
    auth.set_custom_user_claims(user.uid, {
        'admin': True
    })

Vai

user, err := client.GetUserByEmail(ctx, "user@admin.example.com")
if err != nil {
	log.Fatal(err)
}
// Confirm user is verified
if user.EmailVerified {
	// Add custom claims for additional privileges.
	// This will be picked up by the user on token refresh or next sign in on new device.
	err := client.SetCustomUserClaims(ctx, user.UID, map[string]interface{}{"admin": true})
	if err != nil {
		log.Fatalf("error setting custom claims %v\n", err)
	}

}

C#

UserRecord user = await FirebaseAuth.DefaultInstance
    .GetUserByEmailAsync("user@admin.example.com");
// Confirm user is verified.
if (user.EmailVerified)
{
    var claims = new Dictionary<string, object>()
    {
        { "admin", true },
    };
    await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(user.Uid, claims);
}

Le rivendicazioni personalizzate possono anche essere modificate in modo incrementale tramite l'SDK Admin:

Node.js

getAuth()
  .getUserByEmail('user@admin.example.com')
  .then((user) => {
    // Add incremental custom claim without overwriting existing claims.
    const currentCustomClaims = user.customClaims;
    if (currentCustomClaims['admin']) {
      // Add level.
      currentCustomClaims['accessLevel'] = 10;
      // Add custom claims for additional privileges.
      return getAuth().setCustomUserClaims(user.uid, currentCustomClaims);
    }
  })
  .catch((error) => {
    console.log(error);
  });

Java

UserRecord user = FirebaseAuth.getInstance()
    .getUserByEmail("user@admin.example.com");
// Add incremental custom claim without overwriting the existing claims.
Map<String, Object> currentClaims = user.getCustomClaims();
if (Boolean.TRUE.equals(currentClaims.get("admin"))) {
  // Add level.
  currentClaims.put("level", 10);
  // Add custom claims for additional privileges.
  FirebaseAuth.getInstance().setCustomUserClaims(user.getUid(), currentClaims);
}

Python

user = auth.get_user_by_email('user@admin.example.com')
# Add incremental custom claim without overwriting existing claims.
current_custom_claims = user.custom_claims
if current_custom_claims.get('admin'):
    # Add level.
    current_custom_claims['accessLevel'] = 10
    # Add custom claims for additional privileges.
    auth.set_custom_user_claims(user.uid, current_custom_claims)

Vai

user, err := client.GetUserByEmail(ctx, "user@admin.example.com")
if err != nil {
	log.Fatal(err)
}
// Add incremental custom claim without overwriting existing claims.
currentCustomClaims := user.CustomClaims
if currentCustomClaims == nil {
	currentCustomClaims = map[string]interface{}{}
}

if _, found := currentCustomClaims["admin"]; found {
	// Add level.
	currentCustomClaims["accessLevel"] = 10
	// Add custom claims for additional privileges.
	err := client.SetCustomUserClaims(ctx, user.UID, currentCustomClaims)
	if err != nil {
		log.Fatalf("error setting custom claims %v\n", err)
	}

}

C#

UserRecord user = await FirebaseAuth.DefaultInstance
    .GetUserByEmailAsync("user@admin.example.com");
// Add incremental custom claims without overwriting the existing claims.
object isAdmin;
if (user.CustomClaims.TryGetValue("admin", out isAdmin) && (bool)isAdmin)
{
    var claims = user.CustomClaims.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
    // Add level.
    var level = 10;
    claims["level"] = level;
    // Add custom claims for additional privileges.
    await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(user.Uid, claims);
}