如何通过FirebaseAdmin SDK从自定义令牌获取ID令牌?

3

如何从自定义令牌中获取ID Token?

[Fact]
public void Get_ID_Token_For_Service_Account_Test()
{
    using (Stream stream = new FileStream(ServiceAccountJsonKeyFilePath, FileMode.Open, FileAccess.Read))
    {
        ServiceAccountCredential credential = ServiceAccountCredential.FromServiceAccountData(stream);
        FirebaseApp.Create(new AppOptions
        {
            Credential = GoogleCredential.FromServiceAccountCredential(credential),
            ServiceAccountId = ServiceAccountId,
        });
        var uid = "Some UID";
        var additionalClaims = new Dictionary<string, object>
        {
            {"dmitry", "pavlov"}
        };
        string customToken = FirebaseAuth.DefaultInstance.CreateCustomTokenAsync(uid, additionalClaims).Result;

        string idToken= null; // How to get this? 

        FirebaseToken token = FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken, CancellationToken.None).Result;

        Assert.NotNull(token);
        Assert.True(token.Claims.ContainsKey("dmitry"));
    }
}

我看到了一些其他语言/平台的示例,但没有C#的示例 - 如何通过当前用户获取ID令牌 - 在客户端检索ID令牌。 但是对于C#,UserRecord和FirebaseAuth都不提供ID令牌。 非常感谢任何指针。


我也提出了这个问题 https://github.com/firebase/firebase-admin-dotnet/issues/110 - Dmitry Pavlov
1个回答

6
我已经找到了获取FirebaseAdmin集成测试中的ID令牌的方法 - 可以查看SignInWithCustomTokenAsync方法。我所需要调整的唯一一件事是基础URL:根据Firebase Auth REST API文档,它应该是

https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken

API KEY是指Web API Key,可以在您的管理控制台的项目设置页面上获得。

因此,调整后的代码如下:

private static async Task<string> SignInWithCustomTokenAsync(string customToken)
{
    string apiKey = "..."; // see above where to get it. 
    var rb = new Google.Apis.Requests.RequestBuilder
    {
        Method = Google.Apis.Http.HttpConsts.Post,
        BaseUri = new Uri($"https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken")
    };
    rb.AddParameter(RequestParameterType.Query, "key", apiKey);
    var request = rb.CreateRequest();
    var jsonSerializer = Google.Apis.Json.NewtonsoftJsonSerializer.Instance;
    var payload = jsonSerializer.Serialize(new SignInRequest
    {
        CustomToken = customToken,
        ReturnSecureToken = true,
    });
    request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
    using (var client = new HttpClient())
    {
        var response = await client.SendAsync(request);
        response.EnsureSuccessStatusCode();
        var json = await response.Content.ReadAsStringAsync();
        var parsed = jsonSerializer.Deserialize<SignInResponse>(json);
        return parsed.IdToken;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接