You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C# Xamarin中获取Firebase当前登录用户的UID

在C# Xamarin中通过Firebase Auth获取UID并操作数据库

一、获取当前登录用户的UID

你使用的firebaseauthentication.net包中,SignInWithEmailAndPasswordAsync方法返回的FirebaseAuth对象包含用户完整信息,其中就有UID。修改登录方法,直接从返回结果中提取并保存UID即可:

static string webAPIKey = "你的Firebase Web API Key";
FirebaseAuthProvider authProvider = new FirebaseAuthProvider(new FirebaseConfig(webAPIKey));

// 推荐用Xamarin.Essentials的SecureStorage存储UID(安全且App重启后不丢失),也可临时用静态变量
public static string CurrentUserUid { get; private set; }

public async Task<string> Login(string email, string pass)
{
    var authResult = await authProvider.SignInWithEmailAndPasswordAsync(email, pass);
    
    if (!string.IsNullOrEmpty(authResult.FirebaseToken))
    {
        // 提取并保存UID
        CurrentUserUid = authResult.User.Uid;
        // 可选:持久化存储到SecureStorage
        // await Xamarin.Essentials.SecureStorage.SetAsync("CurrentUserUid", authResult.User.Uid);
        return authResult.FirebaseToken;
    }
    
    return string.Empty;
}

authResult.User中还包含用户邮箱、显示名等其他信息,可按需调用。

二、通过UID存储数据到Firebase实时数据库

需要配套使用FirebaseDatabase.net包(与firebaseauthentication.net同系列),步骤如下:

  1. 安装NuGet包:
Install-Package FirebaseDatabase.net
  1. 初始化数据库客户端并编写存储方法:
// 替换为你的Firebase实时数据库URL
FirebaseClient firebaseDb = new FirebaseClient("https://你的项目ID.firebaseio.com/");

// 定义用户数据模型
public class UserProfile
{
    public string Email { get; set; }
    public string Nickname { get; set; }
    public int Age { get; set; }
    // 自定义其他业务字段
}

// 将数据存储到对应UID的节点下
public async Task SaveUserProfile(UserProfile profile)
{
    if (string.IsNullOrEmpty(CurrentUserUid))
        throw new InvalidOperationException("用户未登录");
    
    // 数据最终存储路径:/user_profiles/{UID}
    await firebaseDb
        .Child("user_profiles")
        .Child(CurrentUserUid)
        .PutAsync(profile);
}

三、通过UID检索用户数据

同样使用FirebaseDatabase.net,根据UID直接查询对应节点:

public async Task<UserProfile> GetUserProfile()
{
    if (string.IsNullOrEmpty(CurrentUserUid))
        throw new InvalidOperationException("用户未登录");
    
    // 从 /user_profiles/{UID} 路径读取数据
    var profile = await firebaseDb
        .Child("user_profiles")
        .Child(CurrentUserUid)
        .OnceSingleAsync<UserProfile>();
    
    return profile;
}

四、关键安全配置

务必在Firebase控制台设置数据库规则,确保只有登录用户能读写自己的数据:

{
  "rules": {
    "user_profiles": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}

内容的提问来源于stack exchange,提问作者RudyChemik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 04:55:22