Package google provides support for making OAuth2 authorized and authenticated
HTTP requests to Google APIs. It supports the Web server flow, client-side
credentials, service accounts, Google Compute Engine service accounts,
Google App Engine service accounts and workload identity federation
from non-Google cloud platforms.
A brief overview of the package follows. For more information, please read
https://developers.google.com/accounts/docs/OAuth2
and
https://developers.google.com/accounts/docs/application-default-credentials
.
For more information on using workload identity federation, refer to
https://cloud.google.com/iam/docs/how-to#using-workload-identity-federation
.
OAuth2 Configs
¶
Two functions in this package return golang.org/x/oauth2.Config values from Google credential
data. Google supports two JSON formats for OAuth2 credentials: one is handled by ConfigFromJSON,
the other by JWTConfigFromJSON. The returned Config can be used to obtain a TokenSource or
create an http.Client.
Workload and Workforce Identity Federation
¶
For information on how to use Workload and Workforce Identity Federation, see
golang.org/x/oauth2/google/externalaccount
.
Credentials
¶
The Credentials type represents Google credentials, including Application Default
Credentials.
Use FindDefaultCredentials to obtain Application Default Credentials.
FindDefaultCredentials looks in some well-known places for a credentials file, and
will call AppEngineTokenSource or ComputeTokenSource as needed.
Application Default Credentials also support workload identity federation to
access Google Cloud resources from non-Google Cloud platforms including Amazon
Web Services (AWS), Microsoft Azure or any identity provider that supports
OpenID Connect (OIDC). Workload identity federation is recommended for
non-Google Cloud environments as it avoids the need to download, manage and
store service account private keys locally.
DefaultClient and DefaultTokenSource are convenience methods. They first call FindDefaultCredentials,
then use the credentials to construct an http.Client or an oauth2.TokenSource.
Use CredentialsFromJSON to obtain credentials from either of the two JSON formats
described in OAuth2 Configs, above. The TokenSource in the returned value is the
same as the one obtained from the oauth2.Config returned from ConfigFromJSON or
JWTConfigFromJSON, but the Credentials may contain additional information
that is useful is some circumstances.
package main
import (
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"golang.org/x/oauth2/jwt"
)
func main() {
// Your credentials should be obtained from the Google
// Developer Console (https://console.developers.google.com).
conf := &jwt.Config{
Email: "xxx@developer.gserviceaccount.com",
// The contents of your RSA private key or your PEM file
// that contains a private key.
// If you have a p12 file instead, you
// can use `openssl` to export the private key into a pem file.
//
// $ openssl pkcs12 -in key.p12 -passin pass:notasecret -out key.pem -nodes
//
// The field only supports PEM containers with no passphrase.
// The openssl command will convert p12 keys to passphrase-less PEM containers.
PrivateKey: []byte("-----BEGIN RSA PRIVATE KEY-----..."),
Scopes: []string{
"https://www.googleapis.com/auth/bigquery",
"https://www.googleapis.com/auth/blogger",
},
TokenURL: google.JWTTokenURL,
// If you would like to impersonate a user, you can
// create a transport with a subject. The following GET
// request will be made on the behalf of user@example.com.
// Optional.
Subject: "user@example.com",
}
// Initiate an http.Client, the following GET request will be
// authorized and authenticated on the behalf of user@example.com.
client := conf.Client(oauth2.NoContext)
client.Get("...")
}
Output:
package main
import (
"fmt"
"log"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
func main() {
// Your credentials should be obtained from the Google
// Developer Console (https://console.developers.google.com).
conf := &oauth2.Config{
ClientID: "YOUR_CLIENT_ID",
ClientSecret: "YOUR_CLIENT_SECRET",
RedirectURL: "YOUR_REDIRECT_URL",
Scopes: []string{
"https://www.googleapis.com/auth/bigquery",
"https://www.googleapis.com/auth/blogger",
},
Endpoint: google.Endpoint,
}
// Redirect user to Google's consent page to ask for permission
// for the scopes specified above.
url := conf.AuthCodeURL("state")
fmt.Printf("Visit the URL for the auth dialog: %v", url)
// Handle the exchange code to initiate a transport.
tok, err := conf.Exchange(oauth2.NoContext, "authorization-code")
if err != nil {
log.Fatal(err)
}
client := conf.Client(oauth2.NoContext, tok)
client.Get("...")
}
Output:
AppEngineTokenSource returns a token source that fetches tokens from either
the current application's service account or from the metadata server,
depending on the App Engine environment. See below for environment-specific
details. If you are implementing a 3-legged OAuth 2.0 flow on App Engine that
involves user accounts, see oauth2.Config instead.
The current version of this library requires at least Go 1.17 to build,
so first generation App Engine runtimes (<= Go 1.9) are unsupported.
Previously, on first generation App Engine runtimes, AppEngineTokenSource
returned a token source that fetches tokens issued to the
current App Engine application's service account. The provided context must have
come from appengine.NewContext.
Second generation App Engine runtimes (>= Go 1.11) and App Engine flexible:
AppEngineTokenSource is DEPRECATED on second generation runtimes and on the
flexible environment. It delegates to ComputeTokenSource, and the provided
context and scopes are not used. Please use DefaultTokenSource (or ComputeTokenSource,
which DefaultTokenSource will use in this case) instead.
ComputeTokenSource returns a token source that fetches access tokens
from Google Compute Engine (GCE)'s metadata server. It's only valid to use
this token source if your program is running on a GCE instance.
If no account is specified, "default" is used.
If no scopes are specified, a set of default scopes are automatically granted.
Further information about retrieving access tokens from the GCE metadata
server can be found at
https://cloud.google.com/compute/docs/authentication
.
package main
import (
"net/http"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
func main() {
client := &http.Client{
Transport: &oauth2.Transport{
// Fetch from Google Compute Engine's metadata server to retrieve
// an access token for the provided account.
// If no account is specified, "default" is used.
// If no scopes are specified, a set of default scopes
// are automatically granted.
Source: google.ComputeTokenSource("", "https://www.googleapis.com/auth/bigquery"),
},
}
client.Get("...")
}
Output:
ConfigFromJSON uses a Google Developers Console client_credentials.json
file to construct a config.
client_credentials.json can be downloaded from
https://console.developers.google.com
, under "Credentials". Download the Web
application credentials in the JSON format and provide the contents of the
file as jsonKey.
DefaultClient returns an HTTP Client that uses the
DefaultTokenSource to obtain authentication credentials.
package main
import (
"log"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
func main() {
client, err := google.DefaultClient(oauth2.NoContext,
"https://www.googleapis.com/auth/devstorage.full_control")
if err != nil {
log.Fatal(err)
}
client.Get("...")
}
Output:
DefaultTokenSource returns the token source for
"Application Default Credentials".
It is a shortcut for FindDefaultCredentials(ctx, scope).TokenSource.
JWTAccessTokenSourceFromJSON uses a Google Developers service account JSON
key file to read the credentials that authorize and authenticate the
requests, and returns a TokenSource that does not use any OAuth2 flow but
instead creates a JWT and sends that as the access token.
The audience is typically a URL that specifies the scope of the credentials.
Note that this is not a standard OAuth flow, but rather an
optimization supported by a few Google services.
Unless you know otherwise, you should use JWTConfigFromJSON instead.
JWTAccessTokenSourceWithScope uses a Google Developers service account JSON
key file to read the credentials that authorize and authenticate the
requests, and returns a TokenSource that does not use any OAuth2 flow but
instead creates a JWT and sends that as the access token.
The scope is typically a list of URLs that specifies the scope of the
credentials.
Note that this is not a standard OAuth flow, but rather an
optimization supported by a few Google services.
Unless you know otherwise, you should use JWTConfigFromJSON instead.
JWTConfigFromJSON uses a Google Developers service account JSON key file to read
the credentials that authorize and authenticate the requests.
Create a service account on "Credentials" for your project at
https://console.developers.google.com
to download a JSON key file.
package main
import (
"io/ioutil"
"log"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
func main() {
// Your credentials should be obtained from the Google
// Developer Console (https://console.developers.google.com).
// Navigate to your project, then see the "Credentials" page
// under "APIs & Auth".
// To create a service account client, click "Create new Client ID",
// select "Service Account", and click "Create Client ID". A JSON
// key file will then be downloaded to your computer.
data, err := ioutil.ReadFile("/path/to/your-project-key.json")
if err != nil {
log.Fatal(err)
}
conf, err := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/bigquery")
if err != nil {
log.Fatal(err)
}
// Initiate an http.Client. The following GET request will be
// authorized and authenticated on the behalf of
// your service account.
client := conf.Client(oauth2.NoContext)
client.Get("...")
}
Output: