L'SDK Firebase Admin supporta la definizione di attributi personalizzati per gli account utente. In questo modo, nelle app Firebase è possibile implementare varie strategie di controllo dell'accesso, incluso il controllo dell'accesso basato sui ruoli. Questi attributi personalizzati possono fornire 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 di amministratore per accedere a dati e risorse.
- Definire i diversi gruppi a cui appartiene un utente.
- Fornire accesso a più livelli:
- Differenziare gli abbonati a pagamento da quelli non a pagamento.
- Differenziare i moderatori dagli utenti normali.
- Applicazione per insegnanti/studenti e così via.
- Aggiungere un identificatore aggiuntivo a un utente. Ad esempio, un utente Firebase potrebbe essere mappato a un UID diverso in un altro sistema.
Considera un caso in cui vuoi limitare l'accesso al nodo del database "adminContent". Puoi farlo con una ricerca nel database in 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 Realtime Database regola:
{
"rules": {
"adminContent": {
".read": "auth.token.admin === true",
".write": "auth.token.admin === true",
}
}
}
Le attestazioni utente personalizzate sono accessibili tramite i token di autenticazione dell'utente.
Nell'esempio precedente, solo gli utenti con admin impostato su true nell'attestazione 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 di amministratore. Inoltre, il token ID è un meccanismo attendibile per la distribuzione di queste attestazioni personalizzate. Tutti gli accessi autenticati devono 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 da l'SDK Admin.
Impostare e convalidare le attestazioni utente personalizzate tramite l'SDK Admin
Le attestazioni personalizzate possono contenere dati sensibili, pertanto devono essere impostate solo da un ambiente server con privilegi 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 attestazioni personalizzate non deve contenere nomi di chiavi riservate OIDC o nomi riservati di Firebase. Il payload non deve superare i 1000 byte. Le attestazioni personalizzate devono essere serializzabili in JSON. I tipi supportati includono stringhe, numeri, valori booleani, array, oggetti e valori null. I tipi non supportati, come Date, undefined, funzioni o altri valori non JSON, genereranno errori.
Un token ID inviato a un server di backend può confermare l'identità e il livello di accesso dell'utente utilizzando l'SDK Admin come segue:
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 attestazioni 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 attestazioni personalizzate di un utente passando null per customClaims.
Propagare le attestazioni personalizzate al client
Dopo che le nuove attestazioni sono state 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 esegue l'accesso o la riautenticazione dopo la modifica delle attestazioni personalizzate. Il token ID emesso di conseguenza conterrà le attestazioni più recenti.
- Il token ID 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 attestazioni personalizzate possono essere recuperate solo tramite il token ID dell'utente. L'accesso a queste attestazioni 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 averlo convalidato e analizzato le relative attestazioni. Le attestazioni personalizzate non devono essere inviate direttamente al backend, in quanto non possono essere considerate attendibili al di fuori del token.
Una volta che le attestazioni più recenti sono state propagate al token ID di un utente, puoi ottenerle recuperando il token ID:
JavaScript
import { getAuth } from "firebase/auth";
getAuth().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 attestazioni personalizzate
Le attestazioni personalizzate vengono utilizzate solo per fornire il controllo dell'accesso. Non sono progettate per archiviare dati aggiuntivi (come profilo e altri dati personalizzati). Sebbene possa sembrare un meccanismo pratico, è fortemente sconsigliato, in quanto queste attestazioni 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 attestazioni personalizzate solo per archiviare i dati per il controllo dell'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 attestazioni personalizzate hanno una dimensione limitata. Se passi un payload di attestazioni personalizzate superiore a 1000 byte, verrà generato un errore.
Esempi e casi d'uso
Gli esempi seguenti illustrano le attestazioni personalizzate nel contesto di casi d'uso specifici di Firebase.
Definire i ruoli tramite Firebase Functions durante la creazione dell'utente
In questo esempio, le attestazioni personalizzate vengono impostate per un utente durante la creazione utilizzando Cloud Functions.
Le attestazioni personalizzate possono essere aggiunte utilizzando Cloud Functions e propagate immediatamente
con Realtime Database. La funzione viene chiamata solo al momento della registrazione utilizzando un trigger onCreate. Una volta impostate, le attestazioni personalizzate vengono propagate a tutte le sessioni esistenti e future. La volta successiva che l'utente esegue l'accesso con le credenziali utente, il token contiene le attestazioni personalizzate.
Implementazione lato client (JavaScript)
import { GoogleAuthProvider, signInWithPopup, getAuth, onAuthStateChanged } from "firebase/auth";
import { getDatabase, onValue, ref } from "firebase/database";
const auth = getAuth();
const database = getDatabase();
const provider = new GoogleAuthProvider();
signInWithPopup(auth, provider).catch(error => {
console.log(error);
});
let unsubscribeFn = null;
let metadataRef = null;
onAuthStateChanged(auth, user => {
// Remove previous listener.
if (unsubscribeFn) {
unsubscribeFn();
}
// On user login add new listener.
if (user) {
// Check if refresh is required.
metadataRef = ref(database, 'metadata/' + user.uid + '/refreshTime');
// Subscribe new listener to changes on that node.
unsubscribeFn = onValue(metadataRef, async (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);
});
}
});
Cloud Functions logica
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
}
}
}
}
Definire i ruoli tramite una richiesta HTTP
L'esempio seguente imposta le attestazioni utente personalizzate per un utente che ha appena eseguito l'accesso tramite una richiesta HTTP.
Implementazione lato client (JavaScript)
import { GoogleAuthProvider, signInWithPopup, getAuth, onAuthStateChanged } from "firebase/auth";
import { getDatabase, onValue, ref } from "firebase/database";
const auth = getAuth();
const database = getDatabase();
const provider = new GoogleAuthProvider();
signInWithPopup(auth, 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.
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 eseguire 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. Quando il pagamento viene elaborato correttamente, l'utente viene impostato come abbonato a pagamento tramite l'SDK Admin. Al client viene restituita una risposta HTTP riuscita per forzare l'aggiornamento del token.
Definire i ruoli tramite lo script di backend
È possibile impostare l'esecuzione di uno script ricorrente (non avviato dal client) per aggiornare le attestazioni 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 attestazioni 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);
}