นำเข้าผู้ใช้

Firebase Admin SDK มอบ Auth.importUsers() API สำหรับการนำเข้าผู้ใช้จำนวนมากไปยัง Firebase Authentication ด้วยสิทธิ์ระดับสูง แม้ว่าฟีเจอร์นี้จะพร้อมใช้งานใน Firebase CLI เช่นกัน แต่ Admin SDK ให้คุณอัปโหลดผู้ใช้ที่มีอยู่จากระบบการตรวจสอบสิทธิ์ภายนอกหรือโปรเจ็กต์ Firebase อื่นๆ โดยทางโปรแกรม โดยไม่ต้องสร้างไฟล์ CSV หรือ JSON ระดับกลาง

API การนำเข้าผู้ใช้มีข้อดีดังต่อไปนี้:

  • ความสามารถในการย้ายผู้ใช้จากระบบการตรวจสอบความถูกต้องภายนอกโดยใช้อัลกอริธึมการแฮชรหัสผ่านที่แตกต่างกัน
  • ความสามารถในการย้ายผู้ใช้จากโครงการ Firebase อื่น
  • การเพิ่มประสิทธิภาพเพื่อการดำเนินการนำเข้าจำนวนมากที่รวดเร็วและมีประสิทธิภาพ การดำเนินการนี้ประมวลผลผู้ใช้โดยไม่ต้องตรวจสอบ uid , email , phoneNumber หรือตัวระบุอื่นๆ ที่ซ้ำกัน
  • ความสามารถในการโยกย้ายที่มีอยู่หรือสร้างผู้ใช้ OAuth ใหม่ (Google, Facebook ฯลฯ )
  • ความสามารถในการนำเข้าผู้ใช้ที่มีการอ้างสิทธิ์แบบกำหนดเองจำนวนมากโดยตรง

การใช้งาน

สามารถนำเข้าผู้ใช้ได้สูงสุด 1,000 รายในการเรียก API ครั้งเดียว โปรดทราบว่าการดำเนินการนี้ได้รับการปรับให้เหมาะสมเพื่อความเร็ว และไม่ได้ตรวจสอบ uid , email , phoneNumber และการทำซ้ำตัวระบุที่ไม่ซ้ำกันอื่นๆ การนำเข้าผู้ใช้ที่ขัดแย้งกับ uid ที่มีอยู่จะแทนที่ผู้ใช้ที่มีอยู่ การนำเข้าผู้ใช้ด้วยฟิลด์อื่นที่ซ้ำกัน (เช่น email ) จะส่งผลให้มีผู้ใช้เพิ่มเติมที่มีค่าเท่ากัน ดังนั้น เมื่อคุณใช้ API นี้ คุณต้องแน่ใจว่าคุณไม่ทำซ้ำฟิลด์ที่ไม่ซ้ำกันใดๆ

โหนด js

// Up to 1000 users can be imported at once.
const userImportRecords = [
  {
    uid: 'uid1',
    email: 'user1@example.com',
    passwordHash: Buffer.from('passwordHash1'),
    passwordSalt: Buffer.from('salt1'),
  },
  {
    uid: 'uid2',
    email: 'user2@example.com',
    passwordHash: Buffer.from('passwordHash2'),
    passwordSalt: Buffer.from('salt2'),
  },
  //...
];

ชวา

// Up to 1000 users can be imported at once.
List<ImportUserRecord> users = new ArrayList<>();
users.add(ImportUserRecord.builder()
    .setUid("uid1")
    .setEmail("user1@example.com")
    .setPasswordHash("passwordHash1".getBytes())
    .setPasswordSalt("salt1".getBytes())
    .build());
users.add(ImportUserRecord.builder()
    .setUid("uid2")
    .setEmail("user2@example.com")
    .setPasswordHash("passwordHash2".getBytes())
    .setPasswordSalt("salt2".getBytes())
    .build());

หลาม

# Up to 1000 users can be imported at once.
users = [
    auth.ImportUserRecord(
        uid='uid1',
        email='user1@example.com',
        password_hash=b'password_hash_1',
        password_salt=b'salt1'
    ),
    auth.ImportUserRecord(
        uid='uid2',
        email='user2@example.com',
        password_hash=b'password_hash_2',
        password_salt=b'salt2'
    ),
]

ไป

// Up to 1000 users can be imported at once.
var users []*auth.UserToImport
users = append(users, (&auth.UserToImport{}).
	UID("uid1").
	Email("user1@example.com").
	PasswordHash([]byte("passwordHash1")).
	PasswordSalt([]byte("salt1")))
users = append(users, (&auth.UserToImport{}).
	UID("uid2").
	Email("user2@example.com").
	PasswordHash([]byte("passwordHash2")).
	PasswordSalt([]byte("salt2")))

ค#

//  Up to 1000 users can be imported at once.
var users = new List<ImportUserRecordArgs>()
{
    new ImportUserRecordArgs()
    {
        Uid = "uid1",
        Email = "user1@example.com",
        PasswordHash = Encoding.ASCII.GetBytes("passwordHash1"),
        PasswordSalt = Encoding.ASCII.GetBytes("salt1"),
    },
    new ImportUserRecordArgs()
    {
        Uid = "uid2",
        Email = "user2@example.com",
        PasswordHash = Encoding.ASCII.GetBytes("passwordHash2"),
        PasswordSalt = Encoding.ASCII.GetBytes("salt2"),
    },
};

ในตัวอย่างนี้ มีการระบุตัวเลือกแฮชเพื่อช่วยให้ Firebase ตรวจสอบสิทธิ์ผู้ใช้เหล่านี้อย่างปลอดภัยในครั้งถัดไปที่พวกเขาพยายามลงชื่อเข้าใช้ด้วย Firebase Authentication เมื่อลงชื่อเข้าใช้สำเร็จ Firebase จะแฮชรหัสผ่านของผู้ใช้อีกครั้งด้วยอัลกอริทึมการแฮชของ Firebase ภายใน เรียนรู้เพิ่มเติมเกี่ยวกับช่องที่ต้องกรอกตามอัลกอริทึมด้านล่าง

การตรวจสอบสิทธิ์ Firebase พยายามอัปโหลดรายชื่อผู้ใช้ทั้งหมดที่ระบุ แม้ว่าข้อผิดพลาดเฉพาะของผู้ใช้จะเกิดขึ้นก็ตาม การดำเนินการส่งคืนผลลัพธ์พร้อมสรุปการนำเข้าที่สำเร็จและล้มเหลว รายละเอียดข้อผิดพลาดจะถูกส่งกลับต่อการนำเข้าผู้ใช้ที่ล้มเหลว

โหนด 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.
  });

ชวา

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

หลาม

hash_alg = auth.UserImportHash.hmac_sha256(key=b'secret_key')
try:
    result = auth.import_users(users, hash_alg=hash_alg)
    print('Successfully imported {0} users. Failed to import {1} users.'.format(
        result.success_count, result.failure_count))
    for err in result.errors:
        print('Failed to import {0} due to {1}'.format(users[err.index].uid, err.reason))
except exceptions.FirebaseError:
    # Some unrecoverable error occurred that prevented the operation from running.
    pass

ไป

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

ค#

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 ฯลฯ) ไม่ต้องระบุตัวเลือกการแฮช

นำเข้าผู้ใช้ด้วยรหัสผ่านที่แฮชของ Firebase scrypt

ตามค่าเริ่มต้น Firebase จะใช้ อัลกอริธึมแฮชการเข้ารหัสเวอร์ชัน Firebase ที่ได้รับการแก้ไข เพื่อจัดเก็บรหัสผ่าน การนำเข้ารหัสผ่านที่แฮชด้วยสคริปต์ที่แก้ไขแล้วมีประโยชน์สำหรับการย้ายผู้ใช้จากโปรเจ็กต์ Firebase อื่นที่มีอยู่ ในการทำเช่นนั้น จำเป็นต้องกำหนดพารามิเตอร์ภายในสำหรับโปรเจ็กต์ดั้งเดิม

Firebase สร้างพารามิเตอร์แฮชรหัสผ่านที่ไม่ซ้ำกันสำหรับโปรเจ็กต์ Firebase แต่ละโปรเจ็กต์ หากต้องการเข้าถึงพารามิเตอร์เหล่านี้ ให้ไปที่ แท็บ ผู้ใช้ ในคอนโซล Firebase และเลือก พารามิเตอร์แฮชรหัส ผ่านจากเมนูแบบเลื่อนลงที่มุมขวาบนของรายการตารางผู้ใช้

พารามิเตอร์ที่จำเป็นในการสร้างตัวเลือกแฮชสำหรับอัลกอริทึมนี้ประกอบด้วย:

  • key : คีย์ผู้ลงนามที่ปกติจะมีให้ในการเข้ารหัส base64
  • saltSeparator : ตัวแยกเกลือที่ปกติจะมีให้ในการเข้ารหัส base64 (ไม่บังคับ)
  • rounds : จำนวนรอบที่ใช้ในการแฮรหัสผ่าน
  • memoryCost : ต้นทุนหน่วยความจำที่จำเป็นสำหรับอัลกอริทึมนี้

โหนด js

getAuth()
  .importUsers(
    [
      {
        uid: 'some-uid',
        email: 'user@example.com',
        // 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);
  });

ชวา

try {
  List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder()
      .setUid("some-uid")
      .setEmail("user@example.com")
      .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());
}

หลาม

users = [
    auth.ImportUserRecord(
        uid='some-uid',
        email='user@example.com',
        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)

ไป

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("user@example.com").
		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)
}

ค#

try
{
    var users = new List<ImportUserRecordArgs>()
    {
        new ImportUserRecordArgs()
        {
            Uid = "some-uid",
            Email = "user@example.com",
            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 รองรับอัลกอริธึมการเข้ารหัสมาตรฐานตลอดจนเวอร์ชันที่แก้ไข (ด้านบน) สำหรับอัลกอริธึมการเข้ารหัสมาตรฐาน จำเป็นต้องมีพารามิเตอร์แฮชต่อไปนี้:

  • memoryCost : ต้นทุน CPU/หน่วยความจำของอัลกอริธึมการแฮช
  • parallelization : การขนานของอัลกอริธึมการแปลงแป้นพิมพ์
  • blockSize : ขนาดบล็อก (ปกติ 8) ของอัลกอริทึมการแฮช
  • derivedKeyLength : ความยาวคีย์ที่ได้รับของอัลกอริทึมการแฮช

โหนด js

getAuth()
  .importUsers(
    [
      {
        uid: 'some-uid',
        email: 'user@example.com',
        // 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);
  });

ชวา

try {
  List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder()
      .setUid("some-uid")
      .setEmail("user@example.com")
      .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());
}

หลาม

users = [
    auth.ImportUserRecord(
        uid='some-uid',
        email='user@example.com',
        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)

ไป

users := []*auth.UserToImport{
	(&auth.UserToImport{}).
		UID("some-uid").
		Email("user@example.com").
		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)
}

ค#

try
{
    var users = new List<ImportUserRecordArgs>()
    {
        new ImportUserRecordArgs()
        {
            Uid = "some-uid",
            Email = "user@example.com",
            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 สำหรับอัลกอริธึมการแฮชเหล่านี้ คุณต้องระบุคีย์ผู้ลงนามแฮช

โหนด js

getAuth()
  .importUsers(
    [
      {
        uid: 'some-uid',
        email: 'user@example.com',
        // 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);
  });

ชวา

try {
  List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder()
      .setUid("some-uid")
      .setEmail("user@example.com")
      .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());
}

หลาม

users = [
    auth.ImportUserRecord(
        uid='some-uid',
        email='user@example.com',
        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)

ไป

users := []*auth.UserToImport{
	(&auth.UserToImport{}).
		UID("some-uid").
		Email("user@example.com").
		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)
}

ค#

try
{
    var users = new List<ImportUserRecordArgs>()
    {
        new ImportUserRecordArgs()
        {
            Uid = "some-uid",
            Email = "user@example.com",
            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 ) ที่ใช้แฮชรหัสผ่าน

โหนด js

getAuth()
  .importUsers(
    [
      {
        uid: 'some-uid',
        email: 'user@example.com',
        // 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);
  });

ชวา

try {
  List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder()
      .setUid("some-uid")
      .setEmail("user@example.com")
      .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());
}

หลาม

users = [
    auth.ImportUserRecord(
        uid='some-uid',
        email='user@example.com',
        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)

ไป

users := []*auth.UserToImport{
	(&auth.UserToImport{}).
		UID("some-uid").
		Email("user@example.com").
		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)
}

ค#

try
{
    var users = new List<ImportUserRecordArgs>()
    {
        new ImportUserRecordArgs()
        {
            Uid = "some-uid",
            Email = "user@example.com",
            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 ไม่จำเป็นต้องมีพารามิเตอร์แฮชเพิ่มเติมหรือเกลือของรหัสผ่านต่อผู้ใช้

โหนด js

getAuth()
  .importUsers(
    [
      {
        uid: 'some-uid',
        email: 'user@example.com',
        // 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);
  });

ชวา

try {
  List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder()
      .setUid("some-uid")
      .setEmail("user@example.com")
      .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());
}

หลาม

users = [
    auth.ImportUserRecord(
        uid='some-uid',
        email='user@example.com',
        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)

ไป

users := []*auth.UserToImport{
	(&auth.UserToImport{}).
		UID("some-uid").
		Email("user@example.com").
		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)
}

ค#

try
{
    var users = new List<ImportUserRecordArgs>()
    {
        new ImportUserRecordArgs()
        {
            Uid = "some-uid",
            Email = "user@example.com",
            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 : ต้นทุนหน่วยความจำที่จำเป็นสำหรับอัลกอริทึมนี้มีหน่วยเป็นกิโลไบต์ ต้องน้อยกว่า 32768
  • version : เวอร์ชันของอัลกอริทึม Argon2 ( VERSION_10 หรือ VERSION_13 ) ไม่บังคับ ค่าเริ่มต้นเป็น VERSION_13 หากไม่ได้ระบุ
  • associatedData : ข้อมูลที่เกี่ยวข้องเพิ่มเติม ซึ่งจัดทำเป็นอาร์เรย์ไบต์ ซึ่งต่อท้ายค่าแฮชเพื่อเพิ่มระดับความปลอดภัย ไม่บังคับ ข้อมูลนี้จะถูกเข้ารหัส base64 ก่อนที่จะถูกส่งไปยัง API

ชวา

try {
  List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder()
      .setUid("some-uid")
      .setEmail("user@example.com")
      .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 การอ้างสิทธิ์ที่กำหนดเองและหมายเลขโทรศัพท์ และอื่นๆ

โหนด js

getAuth()
  .importUsers([
    {
      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',
        },
      ],
    },
  ])
  .then((results) => {
    results.errors.forEach((indexedError) => {
      console.log(`Error importing user ${indexedError.index}`);
    });
  })
  .catch((error) => {
    console.log('Error importing users :', error);
  });

ชวา

try {
  List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder()
      .setUid("some-uid")
      .setDisplayName("John Doe")
      .setEmail("johndoe@gmail.com")
      .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("johndoe@gmail.com")
          .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());
}

หลาม

users = [
    auth.ImportUserRecord(
        uid='some-uid',
        display_name='John Doe',
        email='johndoe@gmail.com',
        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='johndoe@gmail.com',
                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)

ไป

users := []*auth.UserToImport{
	(&auth.UserToImport{}).
		UID("some-uid").
		DisplayName("John Doe").
		Email("johndoe@gmail.com").
		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:       "johndoe@gmail.com",
				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)
}

ค#

try
{
    var users = new List<ImportUserRecordArgs>()
    {
        new ImportUserRecordArgs()
        {
            Uid = "some-uid",
            DisplayName = "John Doe",
            Email = "johndoe@gmail.com",
            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 = "johndoe@gmail.com",
                    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}");
}