Özel Hak Talepleri ve Güvenlik Kurallarıyla Erişimi Kontrol Etme

Firebase Admin SDK'sı, kullanıcı hesaplarında özel özelliklerin tanımlanmasını destekler. Bu, çeşitli erişim denetimi stratejilerini uygulamanıza olanak tanır. erişim denetimi dahil olmak üzere pek çok işlevi etkinleştirebilir. Bu özel özellikler kullanıcılara farklı düzeylerde erişim (roller) verebilir ve tarafından gerçekleştirilen işlemlerdir.

Kullanıcı rolleri aşağıdaki yaygın durumlar için tanımlanabilir:

  • Bir kullanıcıya verilere ve kaynaklara erişmesi için yönetici ayrıcalıkları verme.
  • Kullanıcının ait olduğu farklı grupları tanımlama.
  • Çok düzeyli erişim sağlama:
    • Ücretli/ücretsiz aboneleri ayırt etme.
    • Moderatörleri normal kullanıcılardan ayırt etme.
    • Öğretmen/öğrenci uygulaması vb.
  • Kullanıcıya başka bir tanımlayıcı ekleyin. Örneğin, bir Firebase kullanıcısı başka bir sistemde farklı bir UID ile eşlenebilir.

Veritabanı düğümüne erişimi sınırlamak istediğiniz bir örneği inceleyelim. "yoneticiContent." Bunu yapmak için kullanabileceğiniz yönetici kullanıcıları. Ancak aynı hedefe ulaşmak için aşağıdaki Realtime Database kuralına sahip admin adlı bir özel kullanıcı talebi:

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

Özel kullanıcı taleplerine, kullanıcının kimlik doğrulama jetonları aracılığıyla erişilebilir. Yukarıdaki örnekte yalnızca admin değeri olan kullanıcılar jeton hak taleplerinde doğru olarak ayarlanmıştır okuma/yazma olurdu adminContent düğüme erişim. Kimlik jetonu bunlar zaten onay, yönetici kontrolü için ek işlem veya arama gerekmez izin verir. Ayrıca kimlik jetonu, veri teslimi için güvenli bir mekanizmadır izin verilmez. Kimliği doğrulanmış tüm erişimler, kimlik jetonunu önceden doğrulamalıdır. söz konusu istek işlenerek işleme alınır.

Bu sayfada açıklanan kod örnekleri ve çözümler hem tarafından sağlanan sunucu tarafı Firebase Auth API'lerini ve Yönetici SDK'si.

Admin SDK aracılığıyla özel kullanıcı hak taleplerini ayarlayın ve doğrulayın

Özel hak talepleri hassas veriler içerebileceği için yalnızca ayarlanmalıdır Firebase Admin SDK aracılığıyla ayrıcalıklı bir sunucu ortamından çıkarır.

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.

Go

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

Özel hak talepleri nesnesi OIDC ayrılmış anahtar adları veya Firebase'in ayrılmış adları arasından seçim yapabilirsiniz. Özel hak talebi yükü 1.000 baytı aşmamalıdır.

Arka uç sunucusuna gönderilen bir kimlik jetonu, kullanıcının kimliğini ve erişimini onaylayabilir aşağıdaki adımları uygulayarak Admin SDK'yı kullanın:

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

Go

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

Ayrıca kullanıcının özelliğini ekleyin:

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

Go

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

customClaims için null değerini ileterek bir kullanıcının özel hak taleplerini silebilirsiniz.

Özel hak taleplerini müşteriye iletme

Bir kullanıcıda Yönetici SDK'sı aracılığıyla değiştirilen yeni hak talepleri, kullanıcılara aktarılır kimlik jetonu aracılığıyla istemci tarafında kimliği doğrulanmış bir kullanıcıya aşağıdaki yöntemler:

  • Özel hak taleplerinde değişiklik yapıldıktan sonra kullanıcı oturum açar veya kimliğini yeniden doğrular. Sonuç olarak verilen kimlik jetonu, en son hak taleplerini içerir.
  • Mevcut bir kullanıcı oturumunun kimlik jetonu, eski bir jetonun süresi dolduktan sonra yenilenir.
  • Bir kimlik jetonu, currentUser.getIdToken(true) çağrısı yapılarak zorla yenilenir.

İstemcideki özel hak taleplerine erişme

Özel hak talepleri yalnızca kullanıcının kimlik jetonuyla alınabilir. Bunlara erişim veya hak talepleri kullanılarak, kullanıcının rolüne veya erişim düzeyinizdir. Ancak arka uç erişimi her zaman Kimlik aracılığıyla zorunlu kılınmalıdır belirtmelisiniz. Özel hak talepleri, anahtar dışında güvenilir olmadıkları için doğrudan arka uca gönderilir.

En son hak talepleri bir kullanıcının kimlik jetonuna yayıldıktan sonra kimlik jetonunu alma:

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

Özel hak talepleriyle ilgili en iyi uygulamalar

Özel hak talepleri, yalnızca erişim denetimi sağlamak için kullanılır. Proje yöneticilerinin Ek verileri (profil ve diğer özel veriler gibi) depolama. Bu durumda pratik bir mekanizma gibi görünse de, bu yöntem kesinlikle önerilmez çünkü kimlik jetonunda depolanır ve tüm hak talepleri performans sorunlarına kimliği doğrulanmış istekler her zaman oturum açmış kullanıcı.

  • Yalnızca kullanıcı erişimini kontrol etmek amacıyla veri depolamak için özel hak taleplerini kullanın. Diğer tüm veriler, gerçek zamanlı veritabanı veya başka bir sunucu tarafı depolama alanı aracılığıyla ayrı olarak depolanmalıdır.
  • Özel hak taleplerinin boyutu sınırlıdır. 1.000 bayttan büyük özel hak talebi yükünün iletilmesi hataya neden olur.

Örnekler ve kullanım alanları

Aşağıdaki örneklerde, özel hak talepleri bağlamında Firebase kullanım alanları.

Kullanıcı oluşturma sürecinde Firebase Functions aracılığıyla rol tanımlama

Bu örnekte, bir kullanıcı için oluşturma sırasında özel hak talepleri Cloud Functions.

Özel hak talepleri Cloud Functions kullanılarak eklenebilir ve hemen uygulanır ile başlayın. İşlev yalnızca onCreate kullanılarak kayıt yapıldığında çağrılır tetikleyici olur. Özel hak talepleri ayarlandıktan sonra, mevcut tüm ve oturum açın. Kullanıcı, kullanıcı kimlik bilgileriyle bir sonraki oturum açışında özel hak taleplerini içerir.

İstemci tarafı uygulama (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 mantığı

Okuma/yazma işlevi kimliği doğrulanmış kullanıcı eklendiğinden emin olun.

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

Veritabanı kuralları

{
  "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
      }
    }
  }
}

HTTP isteği aracılığıyla rol tanımlama

Aşağıdaki örnekte, HTTP isteği.

İstemci tarafı uygulama (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);
});

Arka uç uygulaması (Yönetici SDK'sı)

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

Mevcut bir kullanıcının erişim düzeyini yükseltirken de aynı akış kullanılabilir. Örneğin, ücretsiz bir kullanıcıyı ücretli aboneliğe yükseltebilirsiniz. Kullanıcının kimliği jeton, ödeme bilgileriyle birlikte bir HTTP aracılığıyla arka uç sunucusuna gönderilir isteği gönderin. Ödeme başarıyla işleme koyulduğunda, kullanıcı ücretli bir ödeme olarak ayarlanır. abonesi olmanız gerekir. Etikete başarılı bir HTTP yanıtı döndürülür. istemcinin jeton yenilemesini zorunlu kılmasını sağlar.

Arka uç komut dosyası aracılığıyla rol tanımlama

Yinelenen bir komut dosyası (istemciden başlatılmayan), kullanıcı özel hak taleplerini güncelle:

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

Go

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

Özel hak talepleri, Admin SDK üzerinden aşamalı olarak da değiştirilebilir:

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)

Go

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