Skip to content

Instantly share code, notes, and snippets.

@jaysephjw
Created October 7, 2022 03:09
Show Gist options
  • Save jaysephjw/38add8b88b0873dbbaf5fda30b0970d8 to your computer and use it in GitHub Desktop.
Save jaysephjw/38add8b88b0873dbbaf5fda30b0970d8 to your computer and use it in GitHub Desktop.
Trying to use googleapis in Dart, but having trouble connecting them to the different authentication flows out there?
import 'package:google_sign_in/google_sign_in.dart';
import 'package:googleapis_auth/auth_io.dart';
import 'package:http/http.dart' as http;
/// Trying to use googleapis, but having trouble connecting all the different libraries together?
/// These functions help get a Client from either:
/// (a) User OAuth credentials via GoogleSignIn, or
/// (b) a Service Account secret via googleapis_auth.
///
/// After that, simple pass the client into the Api object, e.g. `final driveApi = DriveApi(client)`.
/// Get an authorized [http.Client] from a user's credentials via [GoogleSignIn].
///
/// Call with GoogleSignIn.currentUser
Future<http.Client> clientFromGoogleSignIn(GoogleSignInAccount currentUser) async {
final authHeaders = await currentUser.authHeaders;
return _DefaultHeadersClient(authHeaders);
}
/// Get an authorized [http.Client] from a service account's JSON secret.
///
/// WARNING: Service Account credentials shouldn't be shipped in client code.
/// Strongly recommended to only for server-side code, or local unit tests!
///
/// [jsonCredentials] can be a json String, or a Map.
Future<http.Client> clientFromServiceAccount(dynamic jsonCredentials, List<String> scopes) async {
final creds = ServiceAccountCredentials.fromJson(jsonCredentials);
final client = await clientViaServiceAccount(creds, scopes);
return client;
}
/// Little utility [http.Client] implementation to attach the given headers to any request.
/// Here we use it to attach Google auth headers from [GoogleSignInAccount.authHeaders].
class _DefaultHeadersClient extends http.BaseClient {
final Map<String, String> _headers;
final http.Client _client = http.Client();
_DefaultHeadersClient(this._headers);
@override
Future<http.StreamedResponse> send(http.BaseRequest request) {
return _client.send(request..headers.addAll(_headers));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment