Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Googleapis_auth get new access token from refresh Token

I'm using Googleapis_auth to access some Google API, i store credentials in local storage so i can access that api later, but it expires in one hour as a read.

I want to get a new access token after the first one is expired using the saved credential refreshToken, but i don't know how to do that.

This is the code i use to get the user credentials:

var authClient = await clientViaUserConsent(
    ClientId(_clientId, _clientSecret), 
    _scopes,
    (url) { launch(url);}
);
//Save Credentials
await storage.saveCredentials(authClient.credentials.accessToken,
    authClient.credentials.refreshToken);
return authClient;

And this is how i use the saved credentials:

return authenticatedClient(
        http.Client(),
        AccessCredentials(
            AccessToken(credentials["type"], credentials["data"],
                DateTime.tryParse(credentials["expiry"])),
            credentials["refreshToken"],
            _scopes)
);

But as i said above when the credentials expires i have no idea how i make use of the refreshToken to get a new access token.

like image 578
ler Avatar asked Oct 28 '25 13:10

ler


1 Answers

I found the answer:

AccessCredentials newCredentials = await refreshCredentials(
          ClientId(_clientId, _clientSecret),
            AccessCredentials(
                AccessToken(credentials["type"], credentials["data"],
                DateTime.tryParse(credentials["expiry"])),
                credentials["refreshToken"],
                _scopes
            ),
            http.Client()
    );


    return authenticatedClient(
          http.Client(),
          newCredentials
    );
like image 83
ler Avatar answered Oct 31 '25 12:10

ler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!