L'SDK Firebase Admin supporta la definizione di attributi personalizzati negli account utente. In questo modo è possibile implementare varie strategie di controllo degli accessi, tra cui il controllo degli accessi basato su 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 dei diversi gruppi a cui appartiene un utente.
- Fornire un accesso multilivello:
- Differenziare gli abbonati a pagamento da quelli non a pagamento.
- Differenziare i moderatori dagli utenti normali.
- Applicazione per insegnanti/studenti ecc.
- Aggiungi un identificatore aggiuntivo a un utente. Ad esempio, un utente Firebase potrebbe essere mappato a un UID diverso in un altro sistema.
Prendiamo in considerazione un caso in cui vuoi limitare l'accesso al nodo del database "adminContent". Potresti farlo con una ricerca nel database su 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 attestazioni 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 avranno accesso in lettura/scrittura al nodo adminContent. Poiché il token ID contiene già queste
asserzioni, non sono necessarie ulteriori elaborazioni o ricerche per verificare le autorizzazioni
amministrative. Inoltre, il token ID è un meccanismo affidabile per fornire 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 dall'SDK Admin.
Imposta e convalida le attestazioni utente personalizzate tramite l'SDK Admin
Le rivendicazioni 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 rivendicazioni personalizzate non deve contenere nomi di chiavi riservati 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, booleani, array, oggetti e null. I tipi non supportati, come Date, undefined, funzioni o altri valori non JSON, causeranno 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 rivendicazioni personalizzate esistenti di un utente, che sono disponibili come proprietà nell'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.
Propaga le attestazioni personalizzate al client
Dopo che le nuove rivendicazioni sono state modificate su 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 nuovamente l'autenticazione dopo la modifica delle rivendicazioni personalizzate. Il token ID emesso di conseguenza conterrà le rivendicazioni 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).
Accedi 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 averlo convalidato e aver analizzato le relative attestazioni. Le rivendicazioni personalizzate non devono essere inviate direttamente al backend, in quanto non possono essere considerate attendibili al di fuori del token.
Una volta propagate le rivendicazioni più recenti 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 degli accessi. Non sono progettati per archiviare dati aggiuntivi (come il profilo e altri dati personalizzati). Sebbene questo possa sembrare un meccanismo conveniente per farlo, è fortemente sconsigliato, poiché queste rivendicazioni vengono archiviate nel token ID e potrebbero causare problemi di prestazioni, in quanto 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 dimensioni delle rivendicazioni personalizzate sono limitate. Se viene passato un payload di rivendicazioni personalizzate superiore a 1000 byte, verrà generato un errore.
Esempi e casi d'uso
I seguenti esempi 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 rivendicazioni personalizzate vengono impostate su un utente al momento della creazione utilizzando Cloud Functions.
Le rivendicazioni 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 accede con le proprie credenziali, 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);
});
}
});
Logica Cloud Functions
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 le attestazioni utente personalizzate su 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 che esegue l'upgrade da un abbonamento senza costi 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 il pagamento, l'utente viene impostato come abbonato a pagamento tramite l'SDK Admin. Al client viene restituita una risposta HTTP con esito positivo per forzare l'aggiornamento del token.
Definizione dei ruoli tramite 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);
}