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

时间:2019-09-04 12:19:44

标签: c# .net-core firebase-authentication

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

[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令牌-Retrieve ID tokens on clients。但是对于C#,UserRecord和FirebaseAuth都不提供ID令牌。非常感谢任何指针。

1 个答案:

答案 0 :(得分:4)

我已经找到了在FirebaseAdmin集成测试中获取ID令牌的方法-请参见方法SignInWithCustomTokenAsync。我唯一需要调整的是基本URL:根据Firebase Auth REST API文档,它应该是

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

API KEY是指Web API Key,可以在管理控制台的project settings页面上获得。

所以调整后的代码如下:

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