Firebase CreateUser 中的自定义 Uid

Bha*_*ria 5 firebase firebase-realtime-database

我的应用程序结构要求我使用特定的Uid.

我可以在 Firebase Auth 中做到这一点吗?

我的意思是,如果我想用uid=1. 我将与电子邮件和密码一起发送。

是否可以 ?

小智 6

是的,您可以使用 admin sdk:

admin
  .auth()
  .createUser({
    uid: 'some-uid',
    email: 'user@example.com',
    phoneNumber: '+11234567890',
  })
  .then((userRecord) => {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log('Successfully created new user:', userRecord.uid);
  })
  .catch((error) => {
    console.log('Error creating new user:', error);
  });
Run Code Online (Sandbox Code Playgroud)


Mar*_*ark 2

如果您使用自定义令牌进行身份验证,则可以为 Firebase 用户设置 UID。请参阅此https://firebase.google.com/docs/auth/admin/create-custom-tokens#create_custom_tokens_using_a_third-party_jwt_library

这是使用 Ruby 的示例 ( :uid => uid)

require "jwt"

# Get your service account's email address and private key from the JSON key file
$service_account_email = "service-account@my-project-abc123.iam.gserviceaccount.com"
$private_key = OpenSSL::PKey::RSA.new "-----BEGIN PRIVATE KEY-----\n..."

def create_custom_token(uid, is_premium_account)
  now_seconds = Time.now.to_i
  payload = {:iss => $service_account_email,
             :sub => $service_account_email,
             :aud => "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
             :iat => now_seconds,
             :exp => now_seconds+(60*60), # Maximum expiration time is one hour
             :uid => uid,
             :claims => {:premium_account => is_premium_account}}
  JWT.encode payload, $private_key, "RS256"
end
Run Code Online (Sandbox Code Playgroud)