Tài liệu này hướng dẫn bạn cách sử dụng Firebase Admin SDK để quản lý người dùng xác thực đa yếu tố theo phương thức lập trình. Khi quản lý người dùng xác thực đa yếu tố, bạn có quyền truy cập vào nhiều thuộc tính của người dùng hơn so với người dùng xác thực một yếu tố.
Trước khi bắt đầu
Cài đặt Node.js Admin SDK. Các Admin SDK ngôn ngữ khác hiện chưa được hỗ trợ.
Lấy thông tin người dùng
Bạn có thể truy xuất dữ liệu liên quan đến xác thực đa yếu tố của người dùng, chẳng hạn như danh sách các yếu tố thứ hai đã đăng ký, từ đối tượng UserRecord. Để lấy hồ sơ người dùng, hãy gọi getUser() hoặc getUserByEmail().
Ví dụ bên dưới cho thấy một người dùng đã đăng ký xác thực đa yếu tố:
// console.log(userRecord.toJSON());
{
uid: 'some-uid',
displayName: 'John Doe',
email: 'johndoe@gmail.com',
photoURL: 'http://www.example.com/12345678/photo.png',
emailVerified: true,
phoneNumber: '+11234567890',
// Set this user as admin.
customClaims: {admin: true},
// User with Google provider.
providerData: [{
uid: 'google-uid',
email: 'johndoe@gmail.com',
displayName: 'John Doe',
photoURL: 'http://www.example.com/12345678/photo.png',
providerId: 'google.com'
}],
multiFactor: {
enrolledFactors: [
// 2FA with SMS as 2nd factor.
{
uid: '53HG4HG45HG8G04GJ40J4G3J',
phoneNumber: '+16505551234',
displayName: 'Work phone',
enrollmentTime: 'Fri, 22 Sep 2017 01:49:58 GMT',
factorId: 'phone',
},
],
},
};
Lập danh sách người dùng
Đoạn mã bên dưới cho biết cách liệt kê tất cả người dùng và kiểm tra xem họ có đăng ký yếu tố thứ hai hay không:
admin.auth().listUsers(1000, nextPageToken)
.then((listUsersResult) => {
listUsersResult.users.forEach((userRecord) => {
// Multi-factor enrolled users second factors can be retrieved via:
if (userRecord.multiFactor) {
userRecord.multiFactor.enrolledFactors.forEach((enrolledFactor) => {
console.log(userRecord.uid, enrolledFactor.toJSON());
});
}
});
})
.catch((error) => {
console.log('Error listing users:', error);
});
Người dùng được trả về theo lô, được sắp xếp theo uid. Mỗi lô kết quả chứa một danh sách người dùng và một mã thông báo trang tiếp theo dùng để tìm nạp lô tiếp theo.
Khi tất cả người dùng đã được liệt kê, pageToken sẽ không được trả về.
Trường maxResult chỉ định kích thước lô tối đa. Giá trị mặc định và tối đa là 1000.
Tạo người dùng
Gọi createUser() để tạo người dùng mới. Người dùng mới có yếu tố thứ hai phải có địa chỉ email đã xác minh (đặt emailVerified thành true) và sử dụng yếu tố đầu tiên được hỗ trợ để đăng nhập. Mỗi người dùng được phép có tối đa 5 yếu tố thứ hai.
Ví dụ này cho thấy cách tạo người dùng mới có 2 yếu tố thứ hai:
admin.auth().createUser({
uid: '123456789',
email: 'user@example.com',
emailVerified: true,
password: 'password',
multiFactor: {
enrolledFactors: [
// When creating users with phone second factors, the uid and
// enrollmentTime should not be specified. These will be provisioned by
// the Auth server.
// Primary second factor.
{
phoneNumber: '+16505550001',
displayName: 'Corp phone',
factorId: 'phone',
},
// Backup second factor.
{
phoneNumber: '+16505550002',
displayName: 'Personal phone',
factorId: 'phone'
},
],
},
})
.then((userRecord) => {
console.log(userRecord.multiFactor.enrolledFactors);
})
.catch((error) => {
console.log(error);
});
Cập nhật người dùng
Để cập nhật người dùng hiện có, hãy gọi updateUser():
admin.auth().updateUser(uid: '123456789', {
multiFactor: {
enrolledFactors: [
{
// uid will be auto-generated.
phoneNumber: '+16505550003',
displayName: 'Spouse\'s phone',
factorId: 'phone',
},
{
// uid can also be specified. This is useful if a new second factor is added and an
// existing enrolled second factor is kept unmodified.
uid: 'existing-enrolled-mfa-uid',
phoneNumber: '+16505550004',
displayName: 'Personal phone',
factorId: 'phone',
},
{
phoneNumber: '+16505550005',
displayName: 'Backup phone',
factorId: 'phone',
// Enrollment time can also be explicitly specified.
enrollmentTime: new Date().toUTCString(),
},
],
},
})
.then((userRecord) => {
console.log(userRecord.multiFactor.enrolledFactors);
})
.catch((error) => {
console.log(error);
});
Thêm yếu tố thứ hai mới
Việc gọi updateUser() bằng danh sách enrolledFactors sẽ xoá mọi yếu tố thứ hai hiện tại của người dùng. Để thêm yếu tố thứ hai mới trong khi vẫn giữ nguyên các yếu tố hiện có, trước tiên, hãy tra cứu người dùng, sau đó thêm yếu tố mới vào danh sách:
function enrollSecondFactor(userId, secondFactorPhoneNumber, secondFactorDisplayName) {
return admin.auth().getUser(userId)
.then((userRecord) => {
const updatedList = (userRecord.multiFactor &&
userRecord.multiFactor.toJSON().enrolledFactors) || [];
updatedList.push({
phoneNumber: secondFactorPhoneNumber,
displayName: secondFactorDisplayName,
factorId: 'phone',
});
return admin.auth().updateUser(userRecord.uid, {
multiFactor: {
enrolledFactors: updatedList,
},
});
})
.catch((error) => {
console.log(error);
});
}
Xoá yếu tố thứ hai
Để huỷ đăng ký hoàn toàn cho người dùng khỏi xác thực đa yếu tố, hãy đặt enrolledFactors thành null hoặc một mảng trống:
admin.auth().updateUser(uid: '123456789', {
multiFactor: {
enrolledFactors: null,
},
})
.then((userRecord) => {
console.log(userRecord.multiFactor);
})
.catch((error) => {
console.log(error);
});