getToken method

Future<AccessTokenResponse?> getToken({
  1. Client? httpClient,
})

Returns a previously required token, if any, or requires a new one.

If a token already exists but is expired, a new token is generated through the refresh_token grant.

Implementation

Future<AccessTokenResponse?> getToken({http.Client? httpClient}) async {
  httpClient ??= this.httpClient;

  _validateAuthorizationParams();

  var tknResp = await getTokenFromStorage();

  if (tknResp != null) {
    if (tknResp.refreshNeeded()) {
      //The access token is expired
      if (tknResp.hasRefreshToken()) {
        tknResp = await refreshToken(tknResp, httpClient: httpClient);
      } else {
        //No refresh token, fetch a new token
        tknResp = await fetchToken(httpClient: httpClient);
      }
    }
  } else {
    tknResp = await fetchToken(httpClient: httpClient);
  }

  if (!tknResp.isValid()) {
    throw OAuth2Exception(
        'Provider error ${tknResp.httpStatusCode}: ${tknResp.error}',
        errorDescription: tknResp.errorDescription);
  }

  if (!tknResp.isBearer()) {
    throw OAuth2Exception('Only Bearer tokens are currently supported');
  }

  return tknResp;
}