refreshCredentials function

Future<AccessCredentials> refreshCredentials(
  1. ClientId clientId,
  2. AccessCredentials credentials,
  3. Client client, {
  4. AuthEndpoints authEndpoints = const GoogleAuthEndpoints(),
})

Obtains refreshed AccessCredentials for clientId and credentials.

The clientId that you obtain from the API Console Credentials page, as described in Obtain OAuth 2.0 credentials.

client will be used for making the HTTP requests needed to create the returned AccessCredentials.

Implementation

Future<AccessCredentials> refreshCredentials(
  ClientId clientId,
  AccessCredentials credentials,
  Client client, {
  AuthEndpoints authEndpoints = const GoogleAuthEndpoints(),
}) async {
  final refreshToken = credentials.refreshToken;
  if (refreshToken == null) {
    throw ArgumentError('clientId.refreshToken cannot be null.');
  }

  // https://developers.google.com/identity/protocols/oauth2/native-app#offline
  final jsonMap = await client.oauthTokenRequest(
    {
      'client_id': clientId.identifier,
      // Not all providers require a client secret,
      // e.g. https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow#refresh-the-access-token
      if (clientId.secret != null) 'client_secret': clientId.secret!,
      'refresh_token': refreshToken,
      'grant_type': 'refresh_token',
    },
    authEndpoints: authEndpoints,
  );

  final accessToken = parseAccessToken(jsonMap);

  final idToken = jsonMap['id_token'] as String?;

  return AccessCredentials(
    accessToken,
    credentials.refreshToken,
    credentials.scopes,
    idToken: idToken,
  );
}