Xamarin C# - FireBase,使用访问令牌验证 REST 请求

Xamarin C# - FireBase, Authenticate REST Requests with an access token

我正在尝试使用 Firebase ID 令牌访问 Firebase 数据库。根据 Firebase 基础文档,"When a user or device signs in using Firebase Authentication, Firebase creates a corresponding ID token that uniquely identifies them and grants them access to several resources, such as Realtime Database.You can re-use that ID token to authenticate the Realtime Database REST API and make requests on behalf of that user."

用户使用邮箱和密码登录后如何获取ID token?这样我就可以将它传递给 https://<DATABASE_NAME>.firebaseio.com/users/ada/name.json?auth=<ID_TOKEN>

您可以使用 C# await 任务包装器代替 Java 侦听器:

C# 异步/等待样式:

var tokenResult = await FirebaseAuth.GetInstance(fireApp).CurrentUser.GetTokenAsync(true);
Log.Debug(App.TAG, tokenResult.Token);

Android/Java听众风格:

FirebaseAuth.GetInstance(fireApp)
            .CurrentUser
            .GetToken(true)
            .AddOnCompleteListener(this, new GmsTaskCompletion((sender, e) => 
{
    var task = (e as GmsTaskCompletion.GmsTaskEvent).task;
    if (task.IsSuccessful)
    {
        var tokenResult = task.Result as GetTokenResult;
        Log.Debug(App.TAG, tokenResult.Token);
    }
}));

使用此 IOnCompleteListener 实现:

public class GmsTaskCompletion : Java.Lang.Object, IOnCompleteListener
{
    public class GmsTaskEvent : EventArgs
    {
        public readonly Android.Gms.Tasks.Task task;
        public GmsTaskEvent(Android.Gms.Tasks.Task task) => this.task = task;
    }

    readonly EventHandler handler;
    public GmsTaskCompletion(EventHandler handler) => this.handler = handler;
    public void OnComplete(Android.Gms.Tasks.Task task)
    {
        if (handler != null)
            handler.Invoke(this, new GmsTaskEvent(task));
    }
}