googleapis_auth 0.2.4

  • README.md
  • CHANGELOG.md
  • Installing
  • Versions
  • 97

Googleapis Auth

This package provides support for obtaining OAuth2 credentials to access Google APIs.

This package also provides convenience functionality for:

  • obtaining authenticated HTTP clients
  • automatically refreshing OAuth2 credentials

Using this package

Using this package requires creating a Google Cloud Project and obtaining application credentials for the specific application type. The steps required are:

  • Create a new Google Cloud Project on the Google Developers Console
  • Enable all APIs that the application will use on the Google Developers Console (under DevConsole -> Project -> APIs & auth -> APIs)
  • Obtain application credentials for a specific application type on the Google Developers Console (under DevConsole -> Project -> APIs & auth -> Credentials)
  • Use the googleapis_auth package to obtain access credentials / obtain an authenticated HTTP client.

Depending on the application type, there are different ways to achieve the third and fourth step. The following is a list of supported OAuth2 flows with a description of these two steps.

Client-side Web Application

For client-side only web applications a "Client ID" needs to be created (under DevConsole -> Project -> APIs & auth -> Credentials). When creating a new client ID, select the "Web application" type. For client-side only applications, no Redirect URIs are necessary. The Javascript Origins setting must be set to all URLs on which your application will be served (e.g. http://localhost:8080 for local testing).

After the Client Id has been created, you can obtain access credentials via

import "package:googleapis_auth/auth_browser.dart";

...

var id = new ClientId("....apps.googleusercontent.com", null);
var scopes = [...];

// Initialize the browser oauth2 flow functionality.
createImplicitBrowserFlow(id, scopes).then((BrowserOAuth2Flow flow) {
  flow.obtainAccessCredentialsViaUserConsent()
      .then((AccessCredentials credentials) {
    // Credentials are available in [credentials].
    ...
    flow.close();
  });
});

or obtain an authenticated HTTP client via

import "package:googleapis_auth/auth_browser.dart";

...

var id = new ClientId("....apps.googleusercontent.com", null);
var scopes = [...];

// Initialize the browser oauth2 flow functionality.
createImplicitBrowserFlow(id, scopes).then((BrowserOAuth2Flow flow) {
  flow.clientViaUserConsent().then((AuthClient client) {
    // Authenticated and auto refreshing client is available in [client].
    ...
    client.close();
    flow.close();
  });
});

To prevent popup blockers from blocking the user authorization dialog, the methods obtainAccessCredentialsViaUserConsent and clientViaUserConsent should preferably only be called inside an event handler, since most browsers do not block popup windows created in response to a user interaction.

The authenticated HTTP client can now access data on behalf a user for the requested oauth2 scopes.

Installed/Console Application

For installed/console applications a "Client ID" needs to be created (under DevConsole -> Project -> APIs & auth -> Credentials). When creating a new client ID, select the "Installed application -> Other" type.

The redirect URIs for the automatic and manual flow will be configured automatically.

After the Client Id has been created, you can obtain access credentials via

import "package:http/http.dart" as http;
import "package:googleapis_auth/auth_io.dart";

...

var id = new ClientId("....apps.googleusercontent.com", "...");
var scopes = [...];

var client = new http.Client();
obtainAccessCredentialsViaUserConsent(id, scopes, client, prompt)
    .then((AccessCredentials credentials) {
  // Access credentials are available in [credentials].
  // ...
  client.close();
});

void prompt(String url) {
  print("Please go to the following URL and grant access:");
  print("  => $url");
  print("");
}

or obtain an authenticated HTTP client via

import "package:googleapis_auth/auth_io.dart";

...

var id = new ClientId("....apps.googleusercontent.com", "...");
var scopes = [...];

clientViaUserConsent(id, scopes, prompt).then((AuthClient client) {
  // Authenticated and auto refreshing client is available in [client].
  // ...
  client.close();
});

void prompt(String url) {
  print("Please go to the following URL and grant access:");
  print("  => $url");
  print("");
}

In case of misconfigured browsers/proxies or other issues, it is also possible to use a manual flow via obtainAccessCredentialsViaUserConsentManual and clientViaUserConsentManual. But in this case the prompt function needs to complete with a Future<String> which contains the "authorization code". The user obtains the "authorization code" (which is a string of characters) in a browser and needs to copy & paste it to the application. (The prompt function should block until it has gotten the "authorization code" from the user.)

The authenticated HTTP client can now access data on behalf a user for the requested oauth2 scopes.

Autonomous Application / Service Account

If an application wants to act autonomously and access e.g. data from a Google Cloud Project, then a Service Account can be created. In this case no user authorization is involved.

A service account can be created via the "Service account" application type when creating a new Client ID (under DevConsole -> Project -> APIs & auth -> Credentials). It will download a JSON document which contains a private RSA key. That private key is used for obtaining access credentials.

After the service account was created, you can obtain access credentials via

import "package:http/http.dart" as http;
import "package:googleapis_auth/auth_io.dart";

var accountCredentials = new ServiceAccountCredentials.fromJson({
  "private_key_id": "<please fill in>",
  "private_key": "<please fill in>",
  "client_email": "<please fill in>@developer.gserviceaccount.com",
  "client_id": "<please fill in>.apps.googleusercontent.com",
  "type": "service_account"
});
var scopes = [...];

...

var client = new http.Client();
obtainAccessCredentialsViaServiceAccount(accountCredentials, scopes, client)
    .then((AccessCredentials credentials) {
  // Access credentials are available in [credentials].
  // ...
  client.close();
});

or an authenticated HTTP client via

import "package:googleapis_auth/auth_io.dart";

final accountCredentials = new ServiceAccountCredentials.fromJson({
  "private_key_id": "<please fill in>",
  "private_key": "<please fill in>",
  "client_email": "<please fill in>@developer.gserviceaccount.com",
  "client_id": "<please fill in>.apps.googleusercontent.com",
  "type": "service_account"
});
var scopes = [...];

...

clientViaServiceAccount(accountCredentials, scopes).then((AuthClient client) {
  // [client] is an authenticated HTTP client.
  // ...
  client.close();
});

The authenticated HTTP client can now access APIs.

Impersonation

For some APIs the use of a service account also requires to impersonate a user. To support that the ServiceAccountCredentials constructors have an optional argument impersonatedUser to specify the user to impersonate.

One example of this are the Google Apps APIs. See [Perform Google Apps Domain-Wide Delegation of Authority] (https://developers.google.com/admin-sdk/directory/v1/guides/delegation) for information on the additional security configuration required to enable this for a service account.

Autonomous Application / Compute Engine using metadata service

If an application wants to act autonomously and access e.g. data from a Google Cloud Project, then a Service Account can be used. In case the application is running on a ComputeEngine VM it is possible to start a VM with a set of scopes the VM is allowed to use. See the documentation for further information.

Here is an example of using the metadata service for obtaining access credentials on a ComputeEngine VM.

import "package:http/http.dart" as http;
import "package:googleapis_auth/auth_io.dart";

var client = new http.Client();
obtainAccessCredentialsViaMetadataServer(client)
    .then((AccessCredentials credentials) {
  // Access credentials are available in [credentials].
  // ...
  client.close();
});

or an authenticated HTTP client via

import "package:googleapis_auth/auth_io.dart";

clientViaMetadataServer().then((AuthClient client) {
  // [client] is an authenticated HTTP client.
  // ...
  client.close();
});

The authenticated HTTP client can now access APIs.

Accessing Public Data with API Key

It is possible to access some APIs by just using an API key without OAuth2.

A API key can be obtained on the Google Developers Console by creating a Key at the "Public API access" section (under DevConsole -> Project -> APIs & auth -> Credentials).

A key can be created for different application types: For browser applications it is necessary to specify a set of referer URls from which the application would like to access APIs. For server applications it is possible to specify a list of IP ranges from which the client application would like to access APIs.

Note that the ApiKey is used for quota and billing purposes and should not be disclosed to third parties.

Here is an example of getting an HTTP client which uses an API key for making HTTP requests.

import "package:googleapis_auth/auth_io.dart";

var client = clientViaApiKey('<api-key-from-devconsole>');
// [client] can now be used to make REST calls to Google APIs.
// ...
client.close();

More information

More information can be obtained from official Google Developers documentation:

0.2.4

  • Added id_token to AccessCredentials

  • Migrated to Dart 2 BigInt.

0.2.3+6

  • Fix async issue in oauth2 flow implementation

0.2.3+5

  • Support the latest version of crypto package.

0.2.3+4

  • Make package strong-mode compliant.

0.2.3+3

  • Support package:crypto >= 0.9.2

0.2.3+2

  • Use preferred "Metadata-Flavor" HTTP header in MetadataServerAuthorizationFlow instead of the deprecated "X-Google-Metadata-Request" header.

0.2.3

  • Allow ServiceAccountCredentials constructors to take an optional user argument to specify a user to impersonate.

0.2.2

  • Allow ServiceAccountCredentials.fromJson to accept a Map.
  • Cleaned up README.md

0.2.1

  • Added optional force and immediate arguments to runHybridFlow.

0.2.0

  • Renamed forceUserConsent parameter to immediate.
  • Added runHybridFlow function to auth_browser, with corresponding HybridFlowResult class.

0.1.1

  • Add clientViaApiKey functions to auth_io ad auth_browser.

0.1.0

  • First release.

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  googleapis_auth: "^0.2.4"

2. Install it

You can install packages from the command line:

with pub:


$ pub get

Alternatively, your editor might support pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:googleapis_auth/auth.dart';

import 'package:googleapis_auth/auth_browser.dart';

import 'package:googleapis_auth/auth_io.dart';
        
Version Uploaded Documentation Archive
0.2.4 Jan 18, 2018 Go to the documentation of googleapis_auth 0.2.4 Download googleapis_auth 0.2.4 archive
0.2.3+6 Mar 13, 2017 Go to the documentation of googleapis_auth 0.2.3+6 Download googleapis_auth 0.2.3+6 archive
0.2.3+5 Aug 28, 2016 Go to the documentation of googleapis_auth 0.2.3+5 Download googleapis_auth 0.2.3+5 archive
0.2.3+4 Jun 9, 2016 Go to the documentation of googleapis_auth 0.2.3+4 Download googleapis_auth 0.2.3+4 archive
0.2.3+3 May 20, 2016 Go to the documentation of googleapis_auth 0.2.3+3 Download googleapis_auth 0.2.3+3 archive
0.2.3+2 Feb 17, 2016 Go to the documentation of googleapis_auth 0.2.3+2 Download googleapis_auth 0.2.3+2 archive
0.2.3+1 Feb 5, 2015 Go to the documentation of googleapis_auth 0.2.3+1 Download googleapis_auth 0.2.3+1 archive
0.2.3 Feb 5, 2015 Go to the documentation of googleapis_auth 0.2.3 Download googleapis_auth 0.2.3 archive
0.2.2 Nov 24, 2014 Go to the documentation of googleapis_auth 0.2.2 Download googleapis_auth 0.2.2 archive
0.2.1 Nov 12, 2014 Go to the documentation of googleapis_auth 0.2.1 Download googleapis_auth 0.2.1 archive

All 13 versions...

Analysis

This feature is new.
We welcome feedback.
More details: scoring.

We analyzed this package, and provided a score, details, and suggestions below.

  • completed on Feb 3, 2018
  • Dart: 2.0.0-dev.20.0
  • pana: 0.10.1

Scores

Popularity:
Describes how popular the package is relative to other packages. [more]
93 / 100
Health:
Code health derived from static analysis. [more]
100 / 100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100 / 100
Overall score:
Weighted score of the above. [more]
97

Platforms

Detected platforms: web

Platform components identified in package: html, io, js.

Suggestions

  • Package is pre-v1 release.

    While there is nothing inherently wrong with versions of 0.*.*, it usually means that the author is still experimenting with the general direction API.

  • Maintain an example.

    Create a short demo in the example/ directory to show how to use this package. Common file name patterns include: main.dart, example.dart or you could also use googleapis_auth.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.13.0 <2.0.0
crypto >=0.9.2 <3.0.0 2.0.2+1
http >=0.11.1 <0.12.0 0.11.3+16
Transitive dependencies
async 2.0.3
charcode 1.1.1
collection 1.14.5
convert 2.0.1
http_parser 3.1.1
path 1.5.1
source_span 1.4.0
string_scanner 1.0.2
typed_data 1.1.5
Dev dependencies
test ^0.12.18