Dmitry Pavlov
Dmitry Pavlov

Reputation: 28290

How can I get ID Token from custom token via FirebaseAdmin SDK?

How can I get ID Token from custom 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"));
    }
}

I see samples for some other languages/platforms but not for C# - how to get ID token via current user here - Retrieve ID tokens on clients. But for C# neither UserRecord nor FirebaseAuth provides ID Token. Any pointers are much appreciated.

Upvotes: 4

Views: 2412

Answers (1)

Dmitry Pavlov
Dmitry Pavlov

Reputation: 28290

I have found the way to get the ID token in FirebaseAdmin integration tests - see method SignInWithCustomTokenAsync. The only thing I have to adjust was base URL: according to Firebase Auth REST API documentation it should be

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

The API KEY refers to the Web API Key, which can be obtained on the project settings page in your admin console.

So the adjusted code looks like this:

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

Upvotes: 6

Related Questions