question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How can I get ID Token from custom token?

See original GitHub issue

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.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:8

github_iconTop GitHub Comments

1reaction
dmitry-pavlovcommented, Sep 4, 2019

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

The issue is now addressed. So I am closing it.

0reactions
dmitry-pavlovcommented, Jul 22, 2020

@jackle991 you need to perform the POST request to “https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken” as I described above but in JS. As far as I understand Firebase has it implemented as part of SDK for JS https://firebase.google.com/docs/auth/web/custom-auth

Read more comments on GitHub >

github_iconTop Results From Across the Web

Firebase admin sdk: idToken OR custom token verification ...
ID Token for verification: To get this token, you will need to call the function "getIDToken" (for Web). This function will return an...
Read more >
Verify ID Tokens | Firebase Authentication - Google
The Firebase Admin SDK has a built-in method for verifying and decoding ID tokens. If the provided ID token has the correct format,...
Read more >
Get an ID token | Authentication
This page describes some ways to acquire a Google-signed OpenID Connect (OIDC) ID token. You need a Google-signed ID token for the following...
Read more >
(Exchange custom token for an ID and refresh ...
There's now a flow function for getting id token straight from the source – please check it out! You can find the flow...
Read more >
Adding Custom Claims to ID Tokens with Auth0 Actions
Learn how to create a new custom Action that will add a custom claim to your Auth0-issued ID Token.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found