step-up-labs / firebase-authentication-dotnet

C# library for Firebase Authentication
MIT License
376 stars 129 forks source link

Refresh access token #219

Open ngocduong777 opened 2 months ago

ngocduong777 commented 2 months ago

Hello everyone, I have just started learning about Firebase Authentication recently, and as I understand it, the token will expire after 3600 seconds (which is 1 hour) by default and needs to be refreshed. I am building a WPF application, and my code looks like the one below. I am not sure if the code I am writing is correct, but I want the case where the user logs in -> leaves the app open for more than 1 hour, and the token will automatically be refreshed to continue being used. I appreciate all your suggestions.

public AuthenticationStore(FirebaseAuthClient firebaseAuthClient)
{
     _firebaseAuthClient = firebaseAuthClient;
     _firebaseAuthClient.AuthStateChanged += OnAuthStateChanged;
}

private async void OnAuthStateChanged(object? sender, UserEventArgs e)
{
    await Application.Current.Dispatcher.Invoke(async () =>
    {
        if (e.User != null)
        {
            if (e.User.Credential.IsExpired())
            {
                await GetFreshAuthAsync();
            }
        }

    });
}
 public async Task<string> GetFreshAuthAsync()
 {
     if (_firebaseAuthClient.User == null)
     {
         return null;
     }

     string newToken = await _firebaseAuthClient.User.GetIdTokenAsync();
     return newToken;
 }