Firebase Admin SDK 支援在使用者帳戶上定義自訂屬性。這提供了在 Firebase 應用中實施各種存取控制策略的能力,包括基於角色的存取控制。這些自訂屬性可以為使用者提供不同層級的存取權限(角色),這些存取等級在應用程式的安全性規則中強制執行。
可針對以下常見情況定義使用者角色:
- 授予使用者存取資料和資源的管理權限。
- 定義使用者所屬的不同群組。
- 提供多層存取:
- 區分付費/非付費訂戶。
- 將版主與一般用戶區分開來。
- 教師/學生申請等
- 為使用者新增附加標識符。例如,Firebase 使用者可以對應到另一個系統中的不同 UID。
讓我們考慮一下您想要限制對資料庫節點「adminContent」的存取的情況。您可以透過對管理員使用者清單進行資料庫查找來做到這一點。但是,您可以使用名為admin
自訂使用者聲明以及以下即時資料庫規則更有效地實現相同的目標:
{
"rules": {
"adminContent": {
".read": "auth.token.admin === true",
".write": "auth.token.admin === true",
}
}
}
自訂使用者聲明可透過使用者的身份驗證令牌存取。在上面的範例中,只有在令牌聲明中將admin
設為 true 的使用者才具有對adminContent
節點的讀取/寫入存取權限。由於 ID 令牌已包含這些斷言,因此不需要額外的處理或查找來檢查管理員權限。此外,ID 令牌是用於傳遞這些自訂聲明的可信任機制。所有經過身份驗證的存取都必須在處理關聯請求之前驗證 ID 令牌。
本頁中所述的程式碼範例和解決方案取自Admin SDK提供的客戶端 Firebase Auth API 和伺服器端 Auth API。
透過 Admin SDK 設定和驗證自訂使用者聲明
自訂聲明可以包含敏感數據,因此只能由 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.
});
爪哇
// 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.
去
// 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.
自訂聲明物件不應包含任何OIDC保留鍵名稱或Firebase 保留名稱。自訂聲明有效負載不得超過 1000 位元組。
傳送到後端伺服器的 ID 令牌可以使用 Admin SDK 確認使用者的身分和存取級別,如下所示:
Node.js
// Verify the ID token first.
getAuth()
.verifyIdToken(idToken)
.then((claims) => {
if (claims.admin === true) {
// Allow access to requested admin resource.
}
});
爪哇
// 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
去
// 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.
}
}
您也可以檢查使用者現有的自訂聲明,這些聲明可作為使用者物件的屬性使用:
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']);
});
爪哇
// 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'))
去
// 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
傳遞 null 來刪除使用者的自訂聲明。
向客戶傳播自訂聲明
透過 Admin SDK 對使用者修改新聲明後,它們將透過 ID 令牌透過以下方式傳播到用戶端上經過驗證的使用者:
- 自訂聲明修改後,使用者登入或重新進行身份驗證。由此頒發的 ID 令牌將包含最新的聲明。
- 舊令牌過期後,現有使用者會話會刷新其 ID 令牌。
- 透過呼叫
currentUser.getIdToken(true)
強制刷新 ID 令牌。
存取客戶端上的自訂聲明
自訂聲明只能透過使用者的 ID 令牌檢索。根據使用者的角色或存取等級修改客戶端 UI 可能需要存取這些聲明。但是,在驗證 ID 令牌並解析其聲明後,應始終透過 ID 令牌強制執行後端存取。自訂聲明不應直接發送到後端,因為它們在令牌之外無法被信任。
一旦最新的聲明傳播到使用者的 ID 令牌,您就可以透過檢索 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);
});
安卓
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();
}
}
});
迅速
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];
}
}
}];
自訂聲明的最佳實踐
自訂聲明僅用於提供存取控制。它們並非旨在儲存附加資料(例如設定檔和其他自訂資料)。雖然這看起來是一種方便的機制,但強烈建議不要這樣做,因為這些聲明儲存在ID 令牌中,並且可能會導致效能問題,因為所有經過身份驗證的請求始終包含與登入使用者相對應的Firebase ID 令牌。
- 使用自訂聲明來儲存僅用於控制使用者存取的資料。所有其他資料應透過即時資料庫或其他伺服器端儲存單獨儲存。
- 定制索賠的大小有限。傳遞大於 1000 位元組的自訂聲明有效負載將引發錯誤。
範例和用例
以下範例說明了特定 Firebase 使用案例上下文中的自訂聲明。
透過 Firebase Functions 在使用者建立時定義角色
在此範例中,使用 Cloud Functions 在建立使用者時設定自訂聲明。
可以使用雲端功能新增自訂聲明,並透過即時資料庫立即傳播。僅在使用onCreate
觸發器註冊時呼叫該函數。設定自訂聲明後,它們將傳播到所有現有和未來的會話。下次使用者使用使用者憑證登入時,令牌將包含自訂聲明。
客戶端實作(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);
}
});
雲函數邏輯
新增一個新的資料庫節點 (metadata/($uid)},其讀取/寫入僅限於經過驗證的使用者。
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);
}
}
});
資料庫規則
{
"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 請求定義角色
以下範例透過 HTTP 請求為新登入的使用者設定自訂使用者聲明。
客戶端實作(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);
});
後端實作(管理SDK)
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' }));
}
});
升級現有使用者的存取等級時可以使用相同的流程。以免費用戶升級到付費訂閱為例。使用者的 ID 令牌與付款資訊透過 HTTP 請求傳送到後端伺服器。成功處理付款後,用戶將透過 Admin SDK 設定為付費訂閱者。成功的 HTTP 回應將傳回給客戶端以強制刷新令牌。
透過後端腳本定義角色
可以設定執行一個重複腳本(不是從客戶端啟動)來更新使用者自訂聲明:
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);
});
爪哇
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
})
去
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);
}
自訂聲明也可以透過 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);
});
爪哇
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)
去
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);
}