Firebase Admin SDK รองรับการกำหนดแอตทริบิวต์ที่กำหนดเองในบัญชีผู้ใช้ ซึ่งช่วยให้สามารถใช้กลยุทธ์การควบคุมการเข้าถึงต่างๆ รวมถึงการควบคุมการเข้าถึงตามบทบาทในแอป Firebase ได้ แอตทริบิวต์ที่กำหนดเองเหล่านี้สามารถให้สิทธิ์เข้าถึง (บทบาท) ระดับต่างๆ แก่ผู้ใช้ ซึ่งจะมีการบังคับใช้ในกฎความปลอดภัยของแอปพลิเคชัน
คุณกำหนดบทบาทของผู้ใช้สำหรับกรณีทั่วไปต่อไปนี้ได้
- ให้สิทธิ์ระดับผู้ดูแลระบบแก่ผู้ใช้ในการเข้าถึงข้อมูลและทรัพยากร
- กำหนดกลุ่มต่างๆ ที่ผู้ใช้เป็นสมาชิก
- ให้สิทธิ์เข้าถึงหลายระดับ
- แยกความแตกต่างระหว่างสมาชิกแบบชำระเงินกับสมาชิกแบบไม่ชำระเงิน
- แยกความแตกต่างระหว่างผู้ดูแลกับผู้ใช้ทั่วไป
- แอปพลิเคชันสำหรับครู/นักเรียน เป็นต้น
- เพิ่มตัวระบุเพิ่มเติมให้กับผู้ใช้ เช่น ผู้ใช้ Firebase อาจแมปกับ UID อื่นในระบบอื่น
ลองพิจารณากรณีที่คุณต้องการจำกัดการเข้าถึงโหนดฐานข้อมูล "adminContent" คุณสามารถทำได้โดยใช้การค้นหาฐานข้อมูลในรายชื่อผู้ใช้ที่เป็นผู้ดูแลระบบ อย่างไรก็ตาม คุณสามารถบรรลุเป้าหมายเดียวกันได้อย่างมีประสิทธิภาพมากขึ้นโดยใช้
การอ้างสิทธิ์ที่กำหนดเองของผู้ใช้ที่ชื่อว่า admin พร้อมกฎ Realtime Database ต่อไปนี้
{
"rules": {
"adminContent": {
".read": "auth.token.admin === true",
".write": "auth.token.admin === true",
}
}
}
การอ้างสิทธิ์ที่กำหนดเองของผู้ใช้สามารถเข้าถึงได้ผ่านโทเค็นการตรวจสอบสิทธิ์ของผู้ใช้
ในตัวอย่างข้างต้น เฉพาะผู้ใช้ที่มี admin ตั้งค่าเป็น "จริง" ในการอ้างสิทธิ์โทเค็น
เท่านั้นที่จะมีสิทธิ์อ่าน/เขียน
โหนด adminContent เนื่องจากโทเค็นรหัสมีข้อความยืนยันเหล่านี้อยู่แล้ว จึงไม่จำเป็นต้องมีการประมวลผลหรือการค้นหาเพิ่มเติมเพื่อตรวจสอบสิทธิ์ของผู้ดูแลระบบ นอกจากนี้ โทเค็นรหัสยังเป็นกลไกที่เชื่อถือได้สำหรับการส่งการอ้างสิทธิ์ที่กำหนดเองเหล่านี้ การเข้าถึงที่ตรวจสอบสิทธิ์แล้วทั้งหมดต้องตรวจสอบโทเค็นรหัสก่อนประมวลผลคำขอที่เกี่ยวข้อง
ตัวอย่างโค้ดและโซลูชันที่อธิบายไว้ในหน้านี้มาจากทั้ง Firebase Auth API ฝั่งไคลเอ็นต์และ Auth API ฝั่งเซิร์ฟเวอร์ที่ Admin SDK มีให้
ตั้งค่าและตรวจสอบการอ้างสิทธิ์ที่กำหนดเองของผู้ใช้ผ่าน 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.
});
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.
ออบเจ็กต์การอ้างสิทธิ์ที่กำหนดเองต้องไม่มี ชื่อคีย์ที่สงวนไว้ของ OIDC หรือ ชื่อที่สงวนไว้ของ Firebase เพย์โหลดต้องมีขนาดไม่เกิน 1,000 ไบต์ การอ้างสิทธิ์ที่กำหนดเองต้องเป็นแบบอนุกรม JSON ได้ ประเภทที่รองรับ ได้แก่ สตริง ตัวเลข บูลีน อาร์เรย์ ออบเจ็กต์ และค่า Null ประเภทที่ไม่รองรับ เช่น วันที่ ค่าที่ไม่ได้กำหนด ฟังก์ชัน หรือค่าอื่นๆ ที่ไม่ใช่ JSON จะทำให้เกิดข้อผิดพลาด
โทเค็นรหัสที่ส่งไปยังเซิร์ฟเวอร์แบ็กเอนด์สามารถยืนยันตัวตนและระดับการเข้าถึงของผู้ใช้ได้โดยใช้ Admin SDK ดังนี้
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.
}
}
นอกจากนี้ คุณยังตรวจสอบการอ้างสิทธิ์ที่กำหนดเองที่มีอยู่ของผู้ใช้ได้ ซึ่งจะแสดงเป็นพร็อพเพอร์ตี้ในออบเจ็กต์ผู้ใช้
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"]);
คุณสามารถลบการอ้างสิทธิ์ที่กำหนดเองของผู้ใช้ได้โดยส่งค่า Null สำหรับ customClaims
เผยแพร่การอ้างสิทธิ์ที่กำหนดเองไปยังไคลเอ็นต์
หลังจากแก้ไขการอ้างสิทธิ์ใหม่ในผู้ใช้ผ่าน Admin SDK แล้ว ระบบจะเผยแพร่การอ้างสิทธิ์ไปยังผู้ใช้ที่ตรวจสอบสิทธิ์แล้วในฝั่งไคลเอ็นต์ผ่านโทเค็นรหัสด้วยวิธีต่อไปนี้
- ผู้ใช้ลงชื่อเข้าใช้หรือตรวจสอบสิทธิ์อีกครั้งหลังจากแก้ไขการอ้างสิทธิ์ที่กำหนดเอง โทเค็นรหัสที่ออกให้เป็นผลลัพธ์จะมีข้อมูลการอ้างสิทธิ์ล่าสุด
- เซสชันผู้ใช้ที่มีอยู่จะรีเฟรชโทเค็นรหัสหลังจากโทเค็นเก่าหมดอายุ
- ระบบจะรีเฟรชโทเค็นรหัสโดยบังคับโดยการเรียก
currentUser.getIdToken(true)
เข้าถึงการอ้างสิทธิ์ที่กำหนดเองในไคลเอ็นต์
คุณจะดึงข้อมูลการอ้างสิทธิ์ที่กำหนดเองได้ผ่านโทเค็นรหัสของผู้ใช้เท่านั้น คุณอาจต้องเข้าถึงการอ้างสิทธิ์เหล่านี้เพื่อแก้ไข UI ของไคลเอ็นต์ตามบทบาทหรือระดับการเข้าถึงของผู้ใช้ อย่างไรก็ตาม ควรบังคับใช้การเข้าถึงแบ็กเอนด์ผ่านโทเค็นรหัสเสมอหลังจากตรวจสอบและแยกวิเคราะห์การอ้างสิทธิ์แล้ว ไม่ควรส่งการอ้างสิทธิ์ที่กำหนดเองไปยังแบ็กเอนด์โดยตรง เนื่องจากไม่สามารถเชื่อถือได้นอกโทเค็น
เมื่อการอ้างสิทธิ์ล่าสุดเผยแพร่ไปยังโทเค็นรหัสของผู้ใช้แล้ว คุณจะดึงข้อมูลการอ้างสิทธิ์ได้โดยดึงข้อมูลโทเค็นรหัส
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];
}
}
}];
แนวทางปฏิบัติแนะนำสำหรับการอ้างสิทธิ์ที่กำหนดเอง
การอ้างสิทธิ์ที่กำหนดเองใช้เพื่อควบคุมการเข้าถึงเท่านั้น ไม่ได้ออกแบบมาเพื่อจัดเก็บข้อมูลเพิ่มเติม (เช่น โปรไฟล์และข้อมูลที่กำหนดเองอื่นๆ) แม้ว่าวิธีนี้อาจดูเหมือนกลไกที่สะดวก แต่เราไม่แนะนำให้ทำอย่างยิ่ง เนื่องจากระบบจะจัดเก็บการอ้างสิทธิ์เหล่านี้ไว้ในโทเค็นรหัสและอาจทำให้เกิดปัญหาด้านประสิทธิภาพเนื่องจากคำขอที่ตรวจสอบสิทธิ์แล้วทั้งหมดจะมีโทเค็นรหัส Firebase ที่สอดคล้องกับผู้ใช้ที่ลงชื่อเข้าใช้เสมอ
- ใช้การอ้างสิทธิ์ที่กำหนดเองเพื่อจัดเก็บข้อมูลสำหรับการควบคุมการเข้าถึงของผู้ใช้เท่านั้น ควรจัดเก็บข้อมูลอื่นๆ ทั้งหมดแยกกันผ่านฐานข้อมูลเรียลไทม์หรือพื้นที่เก็บข้อมูลฝั่งเซิร์ฟเวอร์อื่นๆ
- การอ้างสิทธิ์ที่กำหนดเองมีขนาดจำกัด การส่งเพย์โหลดการอ้างสิทธิ์ที่กำหนดเองที่มีขนาดมากกว่า 1,000 ไบต์จะทำให้เกิดข้อผิดพลาด
ตัวอย่างและกรณีการใช้งาน
ตัวอย่างต่อไปนี้แสดงการอ้างสิทธิ์ที่กำหนดเองในบริบทของกรณีการใช้งาน Firebase ที่เฉพาะเจาะจง
การกำหนดบทบาทผ่านฟังก์ชันของ Firebase เมื่อสร้างผู้ใช้
ในตัวอย่างนี้ ระบบจะตั้งค่าการอ้างสิทธิ์ที่กำหนดเองในผู้ใช้เมื่อสร้างโดยใช้ Cloud Functions
คุณสามารถเพิ่มการอ้างสิทธิ์ที่กำหนดเองได้โดยใช้ Cloud Functions และเผยแพร่ได้ทันที
ด้วย Realtime Database ฟังก์ชันจะเรียกใช้เมื่อลงชื่อสมัครใช้โดยใช้ทริกเกอร์ onCreate เท่านั้น เมื่อตั้งค่าการอ้างสิทธิ์ที่กำหนดเองแล้ว ระบบจะเผยแพร่การอ้างสิทธิ์ไปยังเซสชันที่มีอยู่และเซสชันในอนาคตทั้งหมด ครั้งถัดไปที่ผู้ใช้ลงชื่อเข้าใช้ด้วยข้อมูลเข้าสู่ระบบของผู้ใช้ โทเค็นจะมีข้อมูลการอ้างสิทธิ์ที่กำหนดเอง
การติดตั้งใช้งานฝั่งไคลเอ็นต์ (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
ระบบจะเพิ่มโหนดฐานข้อมูลใหม่ (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)
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);
});
การติดตั้งใช้งานแบ็กเอนด์ (Admin 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' }));
}
});
คุณสามารถใช้โฟลว์เดียวกันนี้เมื่ออัปเกรดระดับการเข้าถึงของผู้ใช้ที่มีอยู่ เช่น ผู้ใช้แบบฟรีอัปเกรดเป็นการสมัครใช้บริการแบบชำระเงิน ระบบจะส่งโทเค็นรหัสของผู้ใช้พร้อมข้อมูลการชำระเงินไปยังเซิร์ฟเวอร์แบ็กเอนด์ผ่านคำขอ 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);
});
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);
}
นอกจากนี้ คุณยังแก้ไขการอ้างสิทธิ์ที่กำหนดเองได้ทีละรายการผ่าน 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);
});
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);
}