Firebase Admin SDK มี Auth.importUsers() API สำหรับนำเข้าผู้ใช้จำนวนมากไปยัง Firebase Authentication โดยมีสิทธิ์ที่สูงขึ้น แม้ว่าฟีเจอร์นี้จะพร้อมใช้งานใน Firebase CLI ด้วย แต่ Admin SDK ก็ช่วยให้คุณอัปโหลดผู้ใช้ที่มีอยู่จากระบบการตรวจสอบสิทธิ์ภายนอกหรือโปรเจ็กต์ Firebase อื่นๆ ได้โดยอัตโนมัติโดยไม่ต้องสร้างไฟล์ CSV หรือ JSON ระดับกลาง
API การนำเข้าผู้ใช้มีข้อดีดังนี้
- ความสามารถในการย้ายข้อมูลผู้ใช้จากระบบการตรวจสอบสิทธิ์ภายนอกโดยใช้อัลกอริทึมการแฮชรหัสผ่านอื่น
- ความสามารถในการย้ายข้อมูลผู้ใช้จากโปรเจ็กต์ Firebase อื่น
- การเพิ่มประสิทธิภาพเพื่อให้การดำเนินการนำเข้าแบบกลุ่มรวดเร็วและมีประสิทธิภาพ การดำเนินการนี้จะประมวลผลผู้ใช้โดยไม่ต้องตรวจสอบการซ้ำกันของ
uid,email,phoneNumberหรือตัวระบุอื่นๆ - ความสามารถในการย้ายข้อมูลผู้ใช้ OAuth ที่มีอยู่หรือสร้างผู้ใช้ OAuth ใหม่ (Google, Facebook ฯลฯ)
- ความสามารถในการนําเข้าผู้ใช้ที่มีการอ้างสิทธิ์ที่กําหนดเองโดยตรงทีละหลายรายการ
การใช้งาน
นำเข้าผู้ใช้ได้สูงสุด 1,000 รายในการเรียก API ครั้งเดียว โปรดทราบว่าการดำเนินการนี้ ได้รับการเพิ่มประสิทธิภาพเพื่อความเร็วและไม่ได้ตรวจสอบ uid, email, phoneNumber และ การทำซ้ำตัวระบุที่ไม่ซ้ำอื่นๆ การนำเข้าผู้ใช้ที่ซ้ำกับuidที่มีอยู่จะแทนที่ผู้ใช้ที่มีอยู่ การนำเข้าผู้ใช้ที่มีฟิลด์อื่นๆ ซ้ำ (เช่น email) จะส่งผลให้มีผู้ใช้เพิ่มเติมที่มีค่าเดียวกัน ดังนั้นเมื่อใช้ API นี้ คุณต้องตรวจสอบว่าไม่ได้ ทำซ้ำฟิลด์ที่ไม่ซ้ำกัน
Node.js
// Up to 1000 users can be imported at once. const userImportRecords = [ { uid: 'uid1', email: '[email protected]', passwordHash: Buffer.from('passwordHash1'), passwordSalt: Buffer.from('salt1'), }, { uid: 'uid2', email: '[email protected]', passwordHash: Buffer.from('passwordHash2'), passwordSalt: Buffer.from('salt2'), }, //... ]; Java
// Up to 1000 users can be imported at once. List<ImportUserRecord> users = new ArrayList<>(); users.add(ImportUserRecord.builder() .setUid("uid1") .setEmail("[email protected]") .setPasswordHash("passwordHash1".getBytes()) .setPasswordSalt("salt1".getBytes()) .build()); users.add(ImportUserRecord.builder() .setUid("uid2") .setEmail("[email protected]") .setPasswordHash("passwordHash2".getBytes()) .setPasswordSalt("salt2".getBytes()) .build()); Python
# Up to 1000 users can be imported at once. users = [ auth.ImportUserRecord( uid='uid1', email='[email protected]', password_hash=b'password_hash_1', password_salt=b'salt1' ), auth.ImportUserRecord( uid='uid2', email='[email protected]', password_hash=b'password_hash_2', password_salt=b'salt2' ), ] Go
// Up to 1000 users can be imported at once. var users []*auth.UserToImport users = append(users, (&auth.UserToImport{}). UID("uid1"). Email("[email protected]"). PasswordHash([]byte("passwordHash1")). PasswordSalt([]byte("salt1"))) users = append(users, (&auth.UserToImport{}). UID("uid2"). Email("[email protected]"). PasswordHash([]byte("passwordHash2")). PasswordSalt([]byte("salt2"))) C#
// Up to 1000 users can be imported at once. var users = new List<ImportUserRecordArgs>() { new ImportUserRecordArgs() { Uid = "uid1", Email = "[email protected]", PasswordHash = Encoding.ASCII.GetBytes("passwordHash1"), PasswordSalt = Encoding.ASCII.GetBytes("salt1"), }, new ImportUserRecordArgs() { Uid = "uid2", Email = "[email protected]", PasswordHash = Encoding.ASCII.GetBytes("passwordHash2"), PasswordSalt = Encoding.ASCII.GetBytes("salt2"), }, }; ในตัวอย่างนี้ เราได้ระบุตัวเลือกการแฮชเพื่อช่วยให้ Firebase สามารถตรวจสอบสิทธิ์ผู้ใช้เหล่านี้ได้อย่างปลอดภัย ในครั้งถัดไปที่ผู้ใช้พยายามลงชื่อเข้าใช้ด้วย Firebase Authentication เมื่อลงชื่อเข้าใช้สำเร็จ Firebase จะแฮชรหัสผ่านของผู้ใช้อีกครั้งด้วย อัลกอริทึมการแฮชภายในของ Firebase ดูข้อมูลเพิ่มเติมเกี่ยวกับฟิลด์ที่จำเป็นต่ออัลกอริทึมแต่ละรายการได้ที่ด้านล่าง
Firebase Authentication พยายามอัปโหลดรายชื่อผู้ใช้ทั้งหมดที่ระบุแม้ว่าจะเกิดข้อผิดพลาดเฉพาะผู้ใช้ก็ตาม การดำเนินการจะแสดงผลลัพธ์พร้อม สรุปการนำเข้าที่สำเร็จและไม่สำเร็จ ระบบจะแสดงรายละเอียดข้อผิดพลาดต่อการนำเข้าผู้ใช้ที่ไม่สำเร็จ
Node.js
getAuth() .importUsers(userImportRecords, { hash: { algorithm: 'HMAC_SHA256', key: Buffer.from('secretKey'), }, }) .then((userImportResult) => { // The number of successful imports is determined via: userImportResult.successCount. // The number of failed imports is determined via: userImportResult.failureCount. // To get the error details. userImportResult.errors.forEach((indexedError) => { // The corresponding user that failed to upload. console.log( 'Error ' + indexedError.index, ' failed to import: ', indexedError.error ); }); }) .catch((error) => { // Some unrecoverable error occurred that prevented the operation from running. }); Java
UserImportOptions options = UserImportOptions.withHash( HmacSha256.builder() .setKey("secretKey".getBytes()) .build()); try { UserImportResult result = FirebaseAuth.getInstance().importUsers(users, options); System.out.println("Successfully imported " + result.getSuccessCount() + " users"); System.out.println("Failed to import " + result.getFailureCount() + " users"); for (ErrorInfo indexedError : result.getErrors()) { System.out.println("Failed to import user at index: " + indexedError.getIndex() + " due to error: " + indexedError.getReason()); } } catch (FirebaseAuthException e) { // Some unrecoverable error occurred that prevented the operation from running. } Python
hash_alg = auth.UserImportHash.hmac_sha256(key=b'secret_key') try: result = auth.import_users(users, hash_alg=hash_alg) print( f'Successfully imported {result.success_count} users. Failed to import ' f'{result.failure_count} users.') for err in result.errors: print(f'Failed to import {users[err.index].uid} due to {err.reason}') except exceptions.FirebaseError: # Some unrecoverable error occurred that prevented the operation from running. pass Go
client, err := app.Auth(ctx) if err != nil { log.Fatalln("Error initializing Auth client", err) } h := hash.HMACSHA256{ Key: []byte("secretKey"), } result, err := client.ImportUsers(ctx, users, auth.WithHash(h)) if err != nil { log.Fatalln("Unrecoverable error prevented the operation from running", err) } log.Printf("Successfully imported %d users\n", result.SuccessCount) log.Printf("Failed to import %d users\n", result.FailureCount) for _, e := range result.Errors { log.Printf("Failed to import user at index: %d due to error: %s\n", e.Index, e.Reason) } C#
var options = new UserImportOptions() { Hash = new HmacSha256() { Key = Encoding.ASCII.GetBytes("secretKey"), }, }; try { UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options); Console.WriteLine($"Successfully imported {result.SuccessCount} users"); Console.WriteLine($"Failed to import {result.FailureCount} users"); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user at index: {indexedError.Index}" + $" due to error: {indexedError.Reason}"); } } catch (FirebaseAuthException) { // Some unrecoverable error occurred that prevented the operation from running. } หากไม่จำเป็นต้องแฮชรหัสผ่าน (หมายเลขโทรศัพท์ ผู้ใช้โทเค็นที่กำหนดเอง ผู้ใช้ OAuth ฯลฯ) ให้ไม่ต้องระบุตัวเลือกการแฮช
นำเข้าผู้ใช้ที่มีรหัสผ่านที่แฮชด้วย Scrypt ของ Firebase
โดยค่าเริ่มต้น Firebase จะใช้อัลกอริทึมการแฮช scrypt เวอร์ชัน Firebase ที่แก้ไขแล้ว เพื่อจัดเก็บรหัสผ่าน การนำเข้ารหัสผ่านที่แฮชด้วย Scrypt ที่แก้ไขแล้ว มีประโยชน์ในการย้ายข้อมูลผู้ใช้จากโปรเจ็กต์ Firebase อื่นที่มีอยู่ คุณจำเป็นต้องระบุพารามิเตอร์ภายในสำหรับโปรเจ็กต์ดั้งเดิมเพื่อดำเนินการดังกล่าว
Firebase จะสร้างพารามิเตอร์แฮชรหัสผ่านที่ไม่ซ้ำกันสำหรับแต่ละโปรเจ็กต์ Firebase หากต้องการเข้าถึงพารามิเตอร์เหล่านี้ ให้ไปที่แท็บผู้ใช้ ในคอนโซล Firebase แล้วเลือกพารามิเตอร์แฮชรหัสผ่านจาก เมนูแบบเลื่อนลงที่มุมขวาบนของรายการตารางผู้ใช้
พารามิเตอร์ที่จำเป็นในการสร้างตัวเลือกแฮชสำหรับอัลกอริทึมนี้ ได้แก่
key: คีย์ผู้ลงนามซึ่งโดยปกติจะมีการเข้ารหัส Base64saltSeparator: ตัวคั่น Salt ซึ่งโดยปกติจะมีการเข้ารหัส Base64(ไม่บังคับ)rounds: จำนวนรอบที่ใช้ในการแฮชรหัสผ่านmemoryCost: ต้นทุนหน่วยความจำที่จำเป็นสำหรับอัลกอริทึมนี้
Node.js
getAuth() .importUsers( [ { uid: 'some-uid', email: '[email protected]', // Must be provided in a byte buffer. passwordHash: Buffer.from('base64-password-hash', 'base64'), // Must be provided in a byte buffer. passwordSalt: Buffer.from('base64-salt', 'base64'), }, ], { hash: { algorithm: 'SCRYPT', // All the parameters below can be obtained from the Firebase Console's users section. // Must be provided in a byte buffer. key: Buffer.from('base64-secret', 'base64'), saltSeparator: Buffer.from('base64SaltSeparator', 'base64'), rounds: 8, memoryCost: 14, }, } ) .then((results) => { results.errors.forEach((indexedError) => { console.log(`Error importing user ${indexedError.index}`); }); }) .catch((error) => { console.log('Error importing users :', error); }); Java
try { List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder() .setUid("some-uid") .setEmail("[email protected]") .setPasswordHash(BaseEncoding.base64().decode("password-hash")) .setPasswordSalt(BaseEncoding.base64().decode("salt")) .build()); UserImportOptions options = UserImportOptions.withHash( Scrypt.builder() // All the parameters below can be obtained from the Firebase Console's "Users" // section. Base64 encoded parameters must be decoded into raw bytes. .setKey(BaseEncoding.base64().decode("base64-secret")) .setSaltSeparator(BaseEncoding.base64().decode("base64-salt-separator")) .setRounds(8) .setMemoryCost(14) .build()); UserImportResult result = FirebaseAuth.getInstance().importUsers(users, options); for (ErrorInfo indexedError : result.getErrors()) { System.out.println("Failed to import user: " + indexedError.getReason()); } } catch (FirebaseAuthException e) { System.out.println("Error importing users: " + e.getMessage()); } Python
users = [ auth.ImportUserRecord( uid='some-uid', email='[email protected]', password_hash=base64.urlsafe_b64decode('password_hash'), password_salt=base64.urlsafe_b64decode('salt') ), ] # All the parameters below can be obtained from the Firebase Console's "Users" # section. Base64 encoded parameters must be decoded into raw bytes. hash_alg = auth.UserImportHash.scrypt( key=base64.b64decode('base64_secret'), salt_separator=base64.b64decode('base64_salt_separator'), rounds=8, memory_cost=14 ) try: result = auth.import_users(users, hash_alg=hash_alg) for err in result.errors: print('Failed to import user:', err.reason) except exceptions.FirebaseError as error: print('Error importing users:', error) Go
b64URLdecode := func(s string) []byte { b, err := base64.URLEncoding.DecodeString(s) if err != nil { log.Fatalln("Failed to decode string", err) } return b } b64Stddecode := func(s string) []byte { b, err := base64.StdEncoding.DecodeString(s) if err != nil { log.Fatalln("Failed to decode string", err) } return b } // Users retrieved from Firebase Auth's backend need to be base64URL decoded users := []*auth.UserToImport{ (&auth.UserToImport{}). UID("some-uid"). Email("[email protected]"). PasswordHash(b64URLdecode("password-hash")). PasswordSalt(b64URLdecode("salt")), } // All the parameters below can be obtained from the Firebase Console's "Users" // section. Base64 encoded parameters must be decoded into raw bytes. h := hash.Scrypt{ Key: b64Stddecode("base64-secret"), SaltSeparator: b64Stddecode("base64-salt-separator"), Rounds: 8, MemoryCost: 14, } result, err := client.ImportUsers(ctx, users, auth.WithHash(h)) if err != nil { log.Fatalln("Error importing users", err) } for _, e := range result.Errors { log.Println("Failed to import user", e.Reason) } C#
try { var users = new List<ImportUserRecordArgs>() { new ImportUserRecordArgs() { Uid = "some-uid", Email = "[email protected]", PasswordHash = Encoding.ASCII.GetBytes("password-hash"), PasswordSalt = Encoding.ASCII.GetBytes("salt"), }, }; var options = new UserImportOptions() { // All the parameters below can be obtained from the Firebase Console's "Users" // section. Base64 encoded parameters must be decoded into raw bytes. Hash = new Scrypt() { Key = Encoding.ASCII.GetBytes("base64-secret"), SaltSeparator = Encoding.ASCII.GetBytes("base64-salt-separator"), Rounds = 8, MemoryCost = 14, }, }; UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user: {indexedError.Reason}"); } } catch (FirebaseAuthException e) { Console.WriteLine($"Error importing users: {e.Message}"); } นำเข้าผู้ใช้ที่มีรหัสผ่านที่แฮชด้วย Scrypt มาตรฐาน
Firebase Authentication รองรับอัลกอริทึม scrypt มาตรฐานและ เวอร์ชันที่แก้ไขแล้ว (ด้านบน) สำหรับ อัลกอริทึม Scrypt มาตรฐาน คุณต้องระบุพารามิเตอร์การแฮชต่อไปนี้
memoryCost: ต้นทุน CPU/หน่วยความจำของอัลกอริทึมการแฮชparallelization: การประมวลผลแบบคู่ขนานของอัลกอริทึมการแฮชblockSize: ขนาดบล็อก (ปกติคือ 8) ของอัลกอริทึมการแฮชderivedKeyLength: ความยาวคีย์ที่ได้จากอัลกอริทึมการแฮช
Node.js
getAuth() .importUsers( [ { uid: 'some-uid', email: '[email protected]', // Must be provided in a byte buffer. passwordHash: Buffer.from('password-hash'), // Must be provided in a byte buffer. passwordSalt: Buffer.from('salt'), }, ], { hash: { algorithm: 'STANDARD_SCRYPT', memoryCost: 1024, parallelization: 16, blockSize: 8, derivedKeyLength: 64, }, } ) .then((results) => { results.errors.forEach((indexedError) => { console.log(`Error importing user ${indexedError.index}`); }); }) .catch((error) => { console.log('Error importing users :', error); }); Java
try { List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder() .setUid("some-uid") .setEmail("[email protected]") .setPasswordHash("password-hash".getBytes()) .setPasswordSalt("salt".getBytes()) .build()); UserImportOptions options = UserImportOptions.withHash( StandardScrypt.builder() .setMemoryCost(1024) .setParallelization(16) .setBlockSize(8) .setDerivedKeyLength(64) .build()); UserImportResult result = FirebaseAuth.getInstance().importUsers(users, options); for (ErrorInfo indexedError : result.getErrors()) { System.out.println("Failed to import user: " + indexedError.getReason()); } } catch (FirebaseAuthException e) { System.out.println("Error importing users: " + e.getMessage()); } Python
users = [ auth.ImportUserRecord( uid='some-uid', email='[email protected]', password_hash=b'password_hash', password_salt=b'salt' ), ] hash_alg = auth.UserImportHash.standard_scrypt( memory_cost=1024, parallelization=16, block_size=8, derived_key_length=64) try: result = auth.import_users(users, hash_alg=hash_alg) for err in result.errors: print('Failed to import user:', err.reason) except exceptions.FirebaseError as error: print('Error importing users:', error) Go
users := []*auth.UserToImport{ (&auth.UserToImport{}). UID("some-uid"). Email("[email protected]"). PasswordHash([]byte("password-hash")). PasswordSalt([]byte("salt")), } h := hash.StandardScrypt{ MemoryCost: 1024, Parallelization: 16, BlockSize: 8, DerivedKeyLength: 64, } result, err := client.ImportUsers(ctx, users, auth.WithHash(h)) if err != nil { log.Fatalln("Error importing users", err) } for _, e := range result.Errors { log.Println("Failed to import user", e.Reason) } C#
try { var users = new List<ImportUserRecordArgs>() { new ImportUserRecordArgs() { Uid = "some-uid", Email = "[email protected]", PasswordHash = Encoding.ASCII.GetBytes("password-hash"), PasswordSalt = Encoding.ASCII.GetBytes("salt"), }, }; var options = new UserImportOptions() { Hash = new StandardScrypt() { MemoryCost = 1024, Parallelization = 16, BlockSize = 8, DerivedKeyLength = 64, }, }; UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user: {indexedError.Reason}"); } } catch (FirebaseAuthException e) { Console.WriteLine($"Error importing users: {e.Message}"); } นำเข้าผู้ใช้ที่มีรหัสผ่านที่แฮชด้วย HMAC
อัลกอริทึมการแฮช HMAC ได้แก่ HMAC_MD5, HMAC_SHA1, HMAC_SHA256 และ HMAC_SHA512 สำหรับอัลกอริทึมการแฮชเหล่านี้ คุณต้องระบุคีย์ของโปรแกรมลงนามแฮช
Node.js
getAuth() .importUsers( [ { uid: 'some-uid', email: '[email protected]', // Must be provided in a byte buffer. passwordHash: Buffer.from('password-hash'), // Must be provided in a byte buffer. passwordSalt: Buffer.from('salt'), }, ], { hash: { algorithm: 'HMAC_SHA256', // Must be provided in a byte buffer. key: Buffer.from('secret'), }, } ) .then((results) => { results.errors.forEach((indexedError) => { console.log(`Error importing user ${indexedError.index}`); }); }) .catch((error) => { console.log('Error importing users :', error); }); Java
try { List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder() .setUid("some-uid") .setEmail("[email protected]") .setPasswordHash("password-hash".getBytes()) .setPasswordSalt("salt".getBytes()) .build()); UserImportOptions options = UserImportOptions.withHash( HmacSha256.builder() .setKey("secret".getBytes()) .build()); UserImportResult result = FirebaseAuth.getInstance().importUsers(users, options); for (ErrorInfo indexedError : result.getErrors()) { System.out.println("Failed to import user: " + indexedError.getReason()); } } catch (FirebaseAuthException e) { System.out.println("Error importing users: " + e.getMessage()); } Python
users = [ auth.ImportUserRecord( uid='some-uid', email='[email protected]', password_hash=b'password_hash', password_salt=b'salt' ), ] hash_alg = auth.UserImportHash.hmac_sha256(key=b'secret') try: result = auth.import_users(users, hash_alg=hash_alg) for err in result.errors: print('Failed to import user:', err.reason) except exceptions.FirebaseError as error: print('Error importing users:', error) Go
users := []*auth.UserToImport{ (&auth.UserToImport{}). UID("some-uid"). Email("[email protected]"). PasswordHash([]byte("password-hash")). PasswordSalt([]byte("salt")), } h := hash.HMACSHA256{ Key: []byte("secret"), } result, err := client.ImportUsers(ctx, users, auth.WithHash(h)) if err != nil { log.Fatalln("Error importing users", err) } for _, e := range result.Errors { log.Println("Failed to import user", e.Reason) } C#
try { var users = new List<ImportUserRecordArgs>() { new ImportUserRecordArgs() { Uid = "some-uid", Email = "[email protected]", PasswordHash = Encoding.ASCII.GetBytes("password-hash"), PasswordSalt = Encoding.ASCII.GetBytes("salt"), }, }; var options = new UserImportOptions() { Hash = new HmacSha256() { Key = Encoding.ASCII.GetBytes("secret"), }, }; UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user: {indexedError.Reason}"); } } catch (FirebaseAuthException e) { Console.WriteLine($"Error importing users: {e.Message}"); } นำเข้าผู้ใช้ที่มีรหัสผ่านที่เข้ารหัสแฮช MD5, SHA และ PBKDF
อัลกอริทึมการแฮช MD5, SHA และ PBKDF ได้แก่ MD5, SHA1, SHA256, SHA512, PBKDF_SHA1 และ PBKDF2_SHA256 สำหรับอัลกอริทึมการแฮชเหล่านี้ คุณต้องระบุจำนวนรอบ (ระหว่าง 0 ถึง 8192 สำหรับ MD5 ระหว่าง 1 ถึง 8192 สำหรับ SHA1, SHA256 และ SHA512 และระหว่าง 0 ถึง 120000 สำหรับ PBKDF_SHA1 และ PBKDF2_SHA256) ที่ใช้ในการแฮชรหัสผ่านในตอนแรก หากเดิมใช้ฟังก์ชันแฮชเดียว คุณต้องตั้งค่ารอบเป็น 1
Node.js
getAuth() .importUsers( [ { uid: 'some-uid', email: '[email protected]', // Must be provided in a byte buffer. passwordHash: Buffer.from('password-hash'), // Must be provided in a byte buffer. passwordSalt: Buffer.from('salt'), }, ], { hash: { algorithm: 'PBKDF2_SHA256', rounds: 100000, }, } ) .then((results) => { results.errors.forEach((indexedError) => { console.log(`Error importing user ${indexedError.index}`); }); }) .catch((error) => { console.log('Error importing users :', error); }); Java
try { List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder() .setUid("some-uid") .setEmail("[email protected]") .setPasswordHash("password-hash".getBytes()) .setPasswordSalt("salt".getBytes()) .build()); UserImportOptions options = UserImportOptions.withHash( Pbkdf2Sha256.builder() .setRounds(100000) .build()); UserImportResult result = FirebaseAuth.getInstance().importUsers(users, options); for (ErrorInfo indexedError : result.getErrors()) { System.out.println("Failed to import user: " + indexedError.getReason()); } } catch (FirebaseAuthException e) { System.out.println("Error importing users: " + e.getMessage()); } Python
users = [ auth.ImportUserRecord( uid='some-uid', email='[email protected]', password_hash=b'password_hash', password_salt=b'salt' ), ] hash_alg = auth.UserImportHash.pbkdf2_sha256(rounds=100000) try: result = auth.import_users(users, hash_alg=hash_alg) for err in result.errors: print('Failed to import user:', err.reason) except exceptions.FirebaseError as error: print('Error importing users:', error) Go
users := []*auth.UserToImport{ (&auth.UserToImport{}). UID("some-uid"). Email("[email protected]"). PasswordHash([]byte("password-hash")). PasswordSalt([]byte("salt")), } h := hash.PBKDF2SHA256{ Rounds: 100000, } result, err := client.ImportUsers(ctx, users, auth.WithHash(h)) if err != nil { log.Fatalln("Error importing users", err) } for _, e := range result.Errors { log.Println("Failed to import user", e.Reason) } C#
try { var users = new List<ImportUserRecordArgs>() { new ImportUserRecordArgs() { Uid = "some-uid", Email = "[email protected]", PasswordHash = Encoding.ASCII.GetBytes("password-hash"), PasswordSalt = Encoding.ASCII.GetBytes("salt"), }, }; var options = new UserImportOptions() { Hash = new Pbkdf2Sha256() { Rounds = 100000, }, }; UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user: {indexedError.Reason}"); } } catch (FirebaseAuthException e) { Console.WriteLine($"Error importing users: {e.Message}"); } นำเข้าผู้ใช้ที่มีรหัสผ่านที่แฮชด้วย BCRYPT
สำหรับรหัสผ่านที่แฮชด้วย BCRYPT ไม่จำเป็นต้องใช้พารามิเตอร์แฮชเพิ่มเติมหรือ ค่า Salt ของรหัสผ่านต่อผู้ใช้
Node.js
getAuth() .importUsers( [ { uid: 'some-uid', email: '[email protected]', // Must be provided in a byte buffer. passwordHash: Buffer.from('password-hash'), }, ], { hash: { algorithm: 'BCRYPT', }, } ) .then((results) => { results.errors.forEach((indexedError) => { console.log(`Error importing user ${indexedError.index}`); }); }) .catch((error) => { console.log('Error importing users :', error); }); Java
try { List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder() .setUid("some-uid") .setEmail("[email protected]") .setPasswordHash("password-hash".getBytes()) .setPasswordSalt("salt".getBytes()) .build()); UserImportOptions options = UserImportOptions.withHash(Bcrypt.getInstance()); UserImportResult result = FirebaseAuth.getInstance().importUsers(users, options); for (ErrorInfo indexedError : result.getErrors()) { System.out.println("Failed to import user: " + indexedError.getReason()); } } catch (FirebaseAuthException e) { System.out.println("Error importing users: " + e.getMessage()); } Python
users = [ auth.ImportUserRecord( uid='some-uid', email='[email protected]', password_hash=b'password_hash', password_salt=b'salt' ), ] hash_alg = auth.UserImportHash.bcrypt() try: result = auth.import_users(users, hash_alg=hash_alg) for err in result.errors: print('Failed to import user:', err.reason) except exceptions.FirebaseError as error: print('Error importing users:', error) Go
users := []*auth.UserToImport{ (&auth.UserToImport{}). UID("some-uid"). Email("[email protected]"). PasswordHash([]byte("password-hash")). PasswordSalt([]byte("salt")), } h := hash.Bcrypt{} result, err := client.ImportUsers(ctx, users, auth.WithHash(h)) if err != nil { log.Fatalln("Error importing users", err) } for _, e := range result.Errors { log.Println("Failed to import user", e.Reason) } C#
try { var users = new List<ImportUserRecordArgs>() { new ImportUserRecordArgs() { Uid = "some-uid", Email = "[email protected]", PasswordHash = Encoding.ASCII.GetBytes("password-hash"), PasswordSalt = Encoding.ASCII.GetBytes("salt"), }, }; var options = new UserImportOptions() { Hash = new Bcrypt(), }; UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user: {indexedError.Reason}"); } } catch (FirebaseAuthException e) { Console.WriteLine($"Error importing users: {e.Message}"); } นำเข้าผู้ใช้ที่มีรหัสผ่านที่แฮชด้วย Argon2
คุณสามารถนำเข้าบันทึกผู้ใช้ที่มีรหัสผ่านที่แฮชด้วย Argon2 ได้โดย สร้างออบเจ็กต์แฮช Argon2 โปรดทราบว่าปัจจุบันระบบรองรับเฉพาะ ใน Admin Java SDK
พารามิเตอร์ที่จำเป็นในการสร้างตัวเลือกแฮชสำหรับอัลกอริทึมนี้ ได้แก่
hashLengthBytes: ความยาวของแฮชที่ต้องการเป็นไบต์ โดยระบุเป็นจำนวนเต็มhashType: ตัวแปร Argon2 ที่จะใช้ (ARGON2_D,ARGON2_ID,ARGON2_I)parallelism: ระดับการทำงานแบบคู่ขนานที่ระบุเป็นจำนวนเต็ม ต้องอยู่ระหว่าง 1 ถึง 16 (รวม)iterations: จำนวนการวนซ้ำที่จะดำเนินการ โดยระบุเป็นจำนวนเต็ม ต้องอยู่ระหว่าง 1 ถึง 16 (รวม)memoryCostKib: ต้นทุนหน่วยความจำที่อัลกอริทึมนี้ต้องการในหน่วยกิบบิไบต์ ต้องน้อยกว่า 32768version: เวอร์ชันของอัลกอริทึม Argon2 (VERSION_10หรือVERSION_13) ไม่บังคับ โดยค่าเริ่มต้นจะเป็น VERSION_13 หากไม่ได้ระบุassociatedData: ข้อมูลที่เชื่อมโยงเพิ่มเติมซึ่งระบุเป็นอาร์เรย์ไบต์ที่ต่อท้ายค่าแฮชเพื่อเพิ่มความปลอดภัยอีกชั้น ไม่บังคับ ข้อมูลนี้จะได้รับการเข้ารหัส Base64 ก่อนที่จะส่งไปยัง API
Java
try { List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder() .setUid("some-uid") .setEmail("[email protected]") .setPasswordHash("password-hash".getBytes()) .setPasswordSalt("salt".getBytes()) .build()); UserImportOptions options = UserImportOptions.withHash( Argon2.builder() .setHashLengthBytes(512) .setHashType(Argon2HashType.ARGON2_ID) .setParallelism(8) .setIterations(16) .setMemoryCostKib(2048) .setVersion(Argon2Version.VERSION_10) .setAssociatedData("associated-data".getBytes()) .build()); UserImportResult result = FirebaseAuth.getInstance().importUsers(users, options); for (ErrorInfo indexedError : result.getErrors()) { System.out.println("Failed to import user: " + indexedError.getReason()); } } catch (FirebaseAuthException e) { System.out.println("Error importing users: " + e.getMessage()); } นำเข้าผู้ใช้โดยไม่ใช้รหัสผ่าน
คุณนำเข้าผู้ใช้ได้โดยไม่ต้องใช้รหัสผ่าน ผู้ใช้ที่ไม่มีรหัสผ่านจะนำเข้าได้โดยใช้ร่วมกับผู้ใช้ที่มีผู้ให้บริการ OAuth, การอ้างสิทธิ์ที่กำหนดเอง และหมายเลขโทรศัพท์ เป็นต้น
Node.js
getAuth() .importUsers([ { uid: 'some-uid', displayName: 'John Doe', email: '[email protected]', 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: '[email protected]', displayName: 'John Doe', photoURL: 'http://www.example.com/12345678/photo.png', providerId: 'google.com', }, ], }, ]) .then((results) => { results.errors.forEach((indexedError) => { console.log(`Error importing user ${indexedError.index}`); }); }) .catch((error) => { console.log('Error importing users :', error); }); Java
try { List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder() .setUid("some-uid") .setDisplayName("John Doe") .setEmail("[email protected]") .setPhotoUrl("http://www.example.com/12345678/photo.png") .setEmailVerified(true) .setPhoneNumber("+11234567890") .putCustomClaim("admin", true) // set this user as admin .addUserProvider(UserProvider.builder() // user with Google provider .setUid("google-uid") .setEmail("[email protected]") .setDisplayName("John Doe") .setPhotoUrl("http://www.example.com/12345678/photo.png") .setProviderId("google.com") .build()) .build()); UserImportResult result = FirebaseAuth.getInstance().importUsers(users); for (ErrorInfo indexedError : result.getErrors()) { System.out.println("Failed to import user: " + indexedError.getReason()); } } catch (FirebaseAuthException e) { System.out.println("Error importing users: " + e.getMessage()); } Python
users = [ auth.ImportUserRecord( uid='some-uid', display_name='John Doe', email='[email protected]', photo_url='http://www.example.com/12345678/photo.png', email_verified=True, phone_number='+11234567890', custom_claims={'admin': True}, # set this user as admin provider_data=[ # user with Google provider auth.UserProvider( uid='google-uid', email='[email protected]', display_name='John Doe', photo_url='http://www.example.com/12345678/photo.png', provider_id='google.com' ) ], ), ] try: result = auth.import_users(users) for err in result.errors: print('Failed to import user:', err.reason) except exceptions.FirebaseError as error: print('Error importing users:', error) Go
users := []*auth.UserToImport{ (&auth.UserToImport{}). UID("some-uid"). DisplayName("John Doe"). Email("[email protected]"). PhotoURL("http://www.example.com/12345678/photo.png"). EmailVerified(true). PhoneNumber("+11234567890"). CustomClaims(map[string]interface{}{"admin": true}). // set this user as admin ProviderData([]*auth.UserProvider{ // user with Google provider { UID: "google-uid", Email: "[email protected]", DisplayName: "John Doe", PhotoURL: "http://www.example.com/12345678/photo.png", ProviderID: "google.com", }, }), } result, err := client.ImportUsers(ctx, users) if err != nil { log.Fatalln("Error importing users", err) } for _, e := range result.Errors { log.Println("Failed to import user", e.Reason) } C#
try { var users = new List<ImportUserRecordArgs>() { new ImportUserRecordArgs() { Uid = "some-uid", DisplayName = "John Doe", Email = "[email protected]", PhotoUrl = "http://www.example.com/12345678/photo.png", EmailVerified = true, PhoneNumber = "+11234567890", CustomClaims = new Dictionary<string, object>() { { "admin", true }, // set this user as admin }, UserProviders = new List<UserProvider> { new UserProvider() // user with Google provider { Uid = "google-uid", Email = "[email protected]", DisplayName = "John Doe", PhotoUrl = "http://www.example.com/12345678/photo.png", ProviderId = "google.com", }, }, }, }; UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user: {indexedError.Reason}"); } } catch (FirebaseAuthException e) { Console.WriteLine($"Error importing users: {e.Message}"); }