Controlla l'accesso con attestazioni personalizzate e regole di sicurezza

Firebase Admin SDK supporta la definizione di attributi personalizzati sugli account utente. Ciò offre la possibilità di implementare varie strategie di controllo degli accessi, incluso il controllo degli accessi in base al ruolo, nelle app Firebase. 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 amministrativi per accedere a dati e risorse.
  • Definizione dei diversi gruppi a cui appartiene un utente.
  • Fornire accesso multilivello:
    • Differenziare gli abbonati pagati/non pagati.
    • Differenziare i moderatori dagli utenti regolari.
    • Domanda di insegnante/studente, ecc.
  • Aggiungi un ulteriore identificatore su un utente. Ad esempio, un utente Firebase potrebbe associarsi a un UID diverso in un altro sistema.

Consideriamo il caso in cui si desidera 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 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 affidabile 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 di autenticazione Firebase lato client che sulle API di autenticazione lato server fornite da Admin SDK .

Imposta e convalida le attestazioni utente personalizzate tramite Admin SDK

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

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

Giava

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

Pitone

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

Andare

// 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 attestazioni personalizzate non deve contenere nomi di chiavi riservate OIDC o nomi riservati Firebase . Il payload delle richieste personalizzate non deve superare i 1000 byte.

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

Node.js

// Verify the ID token first.
getAuth()
  .verifyIdToken(idToken)
  .then((claims) => {
    if (claims.admin === true) {
      // Allow access to requested admin resource.
    }
  });

Giava

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

Pitone

# Verify the ID token first.
claims = auth.verify_id_token(id_token)
if claims['admin'] is True:
    # Allow access to requested admin resource.
    pass

Andare

// 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, che sono disponibili come proprietà sull'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']);
  });

Giava

// Lookup the user associated with the specified uid.
UserRecord user = FirebaseAuth.getInstance().getUser(uid);
System.out.println(user.getCustomClaims().get("admin"));

Pitone

# 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'))

Andare

// 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"]);

È possibile eliminare le attestazioni personalizzate di un utente passando null per customClaims .

Propagare attestazioni personalizzate al client

Dopo che le nuove attestazioni vengono modificate su un utente tramite Admin SDK, 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 attestazioni personalizzate. Il token ID emesso di conseguenza conterrà le ultime attestazioni.
  • Una sessione utente esistente ottiene il token ID aggiornato dopo la scadenza del token precedente.
  • L'aggiornamento forzato di un token ID viene effettuato chiamando currentUser.getIdToken(true) .

Accedi 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 sue attestazioni. Le attestazioni personalizzate non devono essere inviate direttamente al back-end, poiché non possono essere considerate attendibili al di fuori del token.

Una volta che le ultime attestazioni si sono 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);
  });

Androide

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();
    }
  }
});

Veloce

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()
  }
})

Obiettivo-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 progettati per memorizzare dati aggiuntivi (come profilo e altri dati personalizzati). Anche se questo può sembrare un meccanismo conveniente per farlo, è fortemente sconsigliato poiché queste attestazioni sono 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 effettuato l'accesso.

  • Utilizzare attestazioni 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 altro archivio lato server.
  • Le richieste personalizzate hanno dimensioni limitate. Il passaggio di un payload di attestazioni personalizzate maggiore di 1000 byte genererà un errore.

Esempi e casi d'uso

Gli esempi seguenti illustrano attestazioni personalizzate nel contesto di casi d'uso specifici di Firebase.

Definizione dei ruoli tramite Firebase Functions alla creazione dell'utente

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

È possibile aggiungere attestazioni personalizzate utilizzando Cloud Functions e propagarle immediatamente con Realtime Database. La funzione viene chiamata solo al momento dell'iscrizione utilizzando un trigger onCreate . Una volta impostate, le attestazioni personalizzate si propagano a tutte le sessioni esistenti e future. La prossima volta che l'utente accede con le credenziali utente, il token conterrà le attestazioni 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);
  }
});

Logica di Cloud Functions

Viene aggiunto un nuovo nodo del database (metadati/($uid)} con lettura/scrittura limitata 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 della banca dati

{
  "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 su un utente appena connesso 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 di amministrazione)

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 quando si aggiorna il livello di accesso di un utente esistente. Prendiamo ad esempio un utente gratuito che passa a un abbonamento a pagamento. Il token ID dell'utente viene inviato con le informazioni di pagamento al server backend tramite una richiesta HTTP. Quando il pagamento viene elaborato con successo, l'utente viene impostato come abbonato a pagamento tramite Admin SDK. Una risposta HTTP riuscita viene restituita al client per forzare l'aggiornamento del token.

Definizione dei ruoli tramite script backend

È possibile impostare uno script ricorrente (non avviato dal client) per l'esecuzione 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);
  });

Giava

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);
}

Pitone

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

Andare

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 Admin SDK:

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);
  });

Giava

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);
}

Pitone

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)

Andare

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 = new Dictionary<string, object>(user.CustomClaims);
    // Add level.
    claims["level"] = 10;
    // Add custom claims for additional privileges.
    await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(user.Uid, claims);
}