Kiểm soát quyền truy cập bằng thông báo xác nhận quyền sở hữu tuỳ chỉnh và quy tắc bảo mật

SDK quản trị của Firebase hỗ trợ việc xác định các thuộc tính tuỳ chỉnh trên tài khoản người dùng. Điều này mang lại khả năng triển khai nhiều chiến lược kiểm soát quyền truy cập, bao gồm cả biện pháp kiểm soát quyền truy cập dựa trên vai trò, trong các ứng dụng Firebase. Các thuộc tính tuỳ chỉnh này có thể cung cấp cho người dùng nhiều cấp truy cập (vai trò), được thực thi trong các quy tắc bảo mật của ứng dụng.

Bạn có thể xác định vai trò của người dùng cho các trường hợp phổ biến sau:

  • Cấp cho người dùng đặc quyền của quản trị viên để truy cập vào dữ liệu và tài nguyên.
  • Xác định các nhóm khác nhau có người dùng.
  • Cấp quyền truy cập nhiều cấp:
    • Phân biệt người đăng ký có trả phí và người đăng ký không trả phí.
    • Phân biệt người kiểm duyệt với người dùng thông thường.
    • Ứng dụng dành cho giáo viên/học viên, v.v.
  • Thêm giá trị nhận dạng bổ sung cho người dùng. Ví dụ: người dùng Firebase có thể ánh xạ đến một UID khác trong một hệ thống khác.

Hãy xem xét trường hợp bạn muốn giới hạn quyền truy cập vào nút cơ sở dữ liệu "adminContent". Bạn có thể làm việc đó bằng cách tra cứu cơ sở dữ liệu trên danh sách người dùng quản trị. Tuy nhiên, bạn có thể đạt được cùng một mục tiêu đó một cách hiệu quả hơn bằng cách sử dụng thông báo xác nhận quyền sở hữu tuỳ chỉnh của người dùng có tên admin với quy tắc Cơ sở dữ liệu theo thời gian thực sau đây:

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

Bạn có thể truy cập thông báo xác nhận quyền sở hữu tuỳ chỉnh của người dùng qua mã thông báo xác thực của người dùng. Trong ví dụ trên, chỉ những người dùng có admin được đặt thành true trong thông báo xác nhận quyền sở hữu mã thông báo mới có quyền đọc/ghi đối với nút adminContent. Vì mã thông báo mã nhận dạng đã chứa các xác nhận này, nên bạn không cần phải xử lý hoặc tra cứu thêm để kiểm tra quyền của quản trị viên. Ngoài ra, mã thông báo giá trị nhận dạng là một cơ chế đáng tin cậy để gửi các thông báo xác nhận quyền sở hữu tuỳ chỉnh này. Tất cả quyền truy cập đã xác thực đều phải xác thực mã thông báo nhận dạng trước khi xử lý yêu cầu liên quan.

Các mã ví dụ và giải pháp được mô tả trong trang này lấy từ cả API Xác thực Firebase phía máy khách và API Xác thực phía máy chủ do SDK quản trị cung cấp.

Đặt và xác thực thông báo xác nhận quyền sở hữu của người dùng tuỳ chỉnh thông qua SDK dành cho quản trị viên

Thông báo xác nhận quyền sở hữu tuỳ chỉnh có thể chứa dữ liệu nhạy cảm, do đó, bạn chỉ nên đặt các thông báo này từ một môi trường máy chủ đặc quyền bằng SDK dành cho quản trị viên của Firebase.

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.

Tiến hành

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

Đối tượng xác nhận quyền sở hữu tuỳ chỉnh không được chứa bất kỳ tên khoá dành riêng cho OIDC hoặc tên dành riêng của Firebase. Tải trọng của thông báo xác nhận quyền sở hữu tuỳ chỉnh không được vượt quá 1.000 byte.

Mã thông báo giá trị nhận dạng được gửi đến máy chủ phụ trợ có thể xác nhận danh tính và cấp truy cập của người dùng bằng cách sử dụng SDK dành cho quản trị viên như sau:

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

Tiến hành

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

Bạn cũng có thể kiểm tra các thông báo xác nhận quyền sở hữu tuỳ chỉnh hiện có của người dùng. Các thông báo này có sẵn dưới dạng thuộc tính trên đối tượng người dùng:

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

Tiến hành

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

Bạn có thể xoá các thông báo xác nhận quyền sở hữu tuỳ chỉnh của người dùng bằng cách truyền giá trị rỗng cho customClaims.

Truyền đạt các thông báo xác nhận quyền sở hữu tuỳ chỉnh cho khách hàng

Sau khi các thông báo xác nhận quyền sở hữu mới được sửa đổi đối với người dùng thông qua SDK quản trị, các thông báo này sẽ được truyền đến người dùng đã xác thực ở phía máy khách thông qua mã thông báo mã nhận dạng theo các cách sau:

  • Một người dùng đăng nhập hoặc xác thực lại sau khi các thông báo xác nhận quyền sở hữu tuỳ chỉnh được sửa đổi. Do đó, mã thông báo nhận dạng được phát hành sẽ chứa các thông báo xác nhận quyền sở hữu mới nhất.
  • Phiên người dùng hiện có sẽ được làm mới mã thông báo nhận dạng sau khi mã thông báo cũ hết hạn.
  • Mã thông báo giá trị nhận dạng bị buộc làm mới bằng cách gọi currentUser.getIdToken(true).

Truy cập vào thông báo xác nhận quyền sở hữu tuỳ chỉnh trên ứng dụng

Bạn chỉ có thể truy xuất thông báo xác nhận quyền sở hữu tuỳ chỉnh thông qua mã nhận dạng của người dùng. Việc sửa đổi giao diện người dùng ứng dụng khách có thể cần phải có quyền truy cập vào các thông báo xác nhận quyền sở hữu này dựa trên vai trò hoặc cấp truy cập của người dùng. Tuy nhiên, quyền truy cập phụ trợ phải luôn được thực thi thông qua mã thông báo mã nhận dạng sau khi xác thực và phân tích cú pháp các thông báo xác nhận quyền sở hữu. Bạn không nên gửi trực tiếp thông báo xác nhận quyền sở hữu tuỳ chỉnh đến phần phụ trợ, vì chúng không thể đáng tin cậy bên ngoài mã thông báo.

Sau khi các thông báo xác nhận quyền sở hữu mới nhất truyền đến mã nhận dạng của người dùng, bạn có thể nhận các thông báo này bằng cách truy xuất mã nhận dạng:

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

Các phương pháp hay nhất cho thông báo xác nhận quyền sở hữu tuỳ chỉnh

Thông báo xác nhận quyền sở hữu tuỳ chỉnh chỉ được dùng để cung cấp quyền kiểm soát quyền truy cập. Các lớp này không được thiết kế để lưu trữ dữ liệu bổ sung (chẳng hạn như hồ sơ và dữ liệu tuỳ chỉnh khác). Mặc dù có vẻ như đây là một cơ chế thuận tiện để thực hiện, nhưng bạn không nên làm vậy vì các thông báo xác nhận quyền sở hữu này được lưu trữ trong mã thông báo nhận dạng và có thể gây ra vấn đề về hiệu suất vì tất cả các yêu cầu đã được xác thực luôn chứa mã thông báo mã nhận dạng Firebase tương ứng với người dùng đã đăng nhập.

  • Sử dụng thông báo xác nhận quyền sở hữu tuỳ chỉnh để lưu trữ dữ liệu nhằm chỉ kiểm soát quyền truy cập của người dùng. Tất cả dữ liệu khác phải được lưu trữ riêng thông qua cơ sở dữ liệu theo thời gian thực hoặc bộ nhớ phía máy chủ khác.
  • Thông báo xác nhận quyền sở hữu tuỳ chỉnh có kích thước giới hạn. Việc chuyển tải trọng xác nhận quyền sở hữu tuỳ chỉnh lớn hơn 1000 byte sẽ gây ra lỗi.

Ví dụ và trường hợp sử dụng

Các ví dụ sau minh hoạ các thông báo xác nhận quyền sở hữu tuỳ chỉnh trong ngữ cảnh của các trường hợp sử dụng Firebase cụ thể.

Xác định vai trò thông qua Hàm Firebase trong quá trình tạo người dùng

Trong ví dụ này, các thông báo xác nhận quyền sở hữu tuỳ chỉnh được đặt đối với người dùng khi được tạo bằng Chức năng đám mây.

Bạn có thể thêm các thông báo xác nhận quyền sở hữu tuỳ chỉnh bằng Cloud Functions và được truyền ngay lập tức bằng Cơ sở dữ liệu theo thời gian thực. Hàm này chỉ được gọi khi đăng ký bằng điều kiện kích hoạt onCreate. Sau khi được đặt, các thông báo xác nhận quyền sở hữu tuỳ chỉnh sẽ truyền đến tất cả các phiên hiện có và trong tương lai. Vào lần tiếp theo người dùng đăng nhập bằng thông tin đăng nhập của người dùng, mã thông báo sẽ chứa các thông báo xác nhận quyền sở hữu tuỳ chỉnh.

Triển khai phía máy khách (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);
  }
});

Logic Hàm đám mây

Một nút cơ sở dữ liệu mới (metadata/($uid)} với quyền đọc/ghi bị hạn chế đối với người dùng đã xác thực sẽ được thêm.

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

Các quy tắc về cơ sở dữ liệu

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

Xác định vai trò qua yêu cầu HTTP

Ví dụ sau đây đặt các thông báo xác nhận quyền sở hữu tuỳ chỉnh của người dùng đối với một người dùng mới đăng nhập qua một yêu cầu HTTP.

Triển khai phía máy khách (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);
});

Triển khai phần phụ trợ (SDK quản trị)

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

Bạn có thể dùng chính quy trình này khi nâng cấp cấp truy cập của người dùng hiện có. Ví dụ về một người dùng miễn phí nâng cấp lên gói thuê bao có tính phí. Mã thông báo mã nhận dạng của người dùng sẽ được gửi cùng với thông tin thanh toán đến máy chủ phụ trợ thông qua yêu cầu HTTP. Khi khoản thanh toán được xử lý thành công, người dùng được đặt làm người đăng ký có tính phí thông qua SDK dành cho quản trị viên. Một phản hồi HTTP thành công sẽ được trả về cho ứng dụng để buộc làm mới mã thông báo.

Xác định vai trò thông qua tập lệnh phụ trợ

Bạn có thể đặt một tập lệnh định kỳ (không được khởi tạo từ ứng dụng) chạy để cập nhật các thông báo xác nhận quyền sở hữu tuỳ chỉnh của người dùng:

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

Tiến hành

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

Bạn cũng có thể sửa đổi dần các thông báo xác nhận quyền sở hữu tuỳ chỉnh thông qua SDK dành cho quản trị viên:

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)

Tiến hành

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