1// Copyright 2014 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5// Package google provides support for making OAuth2 authorized and 6// authenticated HTTP requests to Google APIs. 7// It supports the Web server flow, client-side credentials, service accounts, 8// Google Compute Engine service accounts, and Google App Engine service 9// accounts. 10// 11// For more information, please read 12// https://developers.google.com/accounts/docs/OAuth2 13// and 14// https://developers.google.com/accounts/docs/application-default-credentials. 15package google 16 17import ( 18 "encoding/json" 19 "errors" 20 "fmt" 21 "strings" 22 "time" 23 24 "cloud.google.com/go/compute/metadata" 25 "golang.org/x/net/context" 26 "golang.org/x/oauth2" 27 "golang.org/x/oauth2/jwt" 28) 29 30// Endpoint is Google's OAuth 2.0 endpoint. 31var Endpoint = oauth2.Endpoint{ 32 AuthURL: "https://accounts.google.com/o/oauth2/auth", 33 TokenURL: "https://accounts.google.com/o/oauth2/token", 34} 35 36// JWTTokenURL is Google's OAuth 2.0 token URL to use with the JWT flow. 37const JWTTokenURL = "https://accounts.google.com/o/oauth2/token" 38 39// ConfigFromJSON uses a Google Developers Console client_credentials.json 40// file to construct a config. 41// client_credentials.json can be downloaded from 42// https://console.developers.google.com, under "Credentials". Download the Web 43// application credentials in the JSON format and provide the contents of the 44// file as jsonKey. 45func ConfigFromJSON(jsonKey []byte, scope ...string) (*oauth2.Config, error) { 46 type cred struct { 47 ClientID string `json:"client_id"` 48 ClientSecret string `json:"client_secret"` 49 RedirectURIs []string `json:"redirect_uris"` 50 AuthURI string `json:"auth_uri"` 51 TokenURI string `json:"token_uri"` 52 } 53 var j struct { 54 Web *cred `json:"web"` 55 Installed *cred `json:"installed"` 56 } 57 if err := json.Unmarshal(jsonKey, &j); err != nil { 58 return nil, err 59 } 60 var c *cred 61 switch { 62 case j.Web != nil: 63 c = j.Web 64 case j.Installed != nil: 65 c = j.Installed 66 default: 67 return nil, fmt.Errorf("oauth2/google: no credentials found") 68 } 69 if len(c.RedirectURIs) < 1 { 70 return nil, errors.New("oauth2/google: missing redirect URL in the client_credentials.json") 71 } 72 return &oauth2.Config{ 73 ClientID: c.ClientID, 74 ClientSecret: c.ClientSecret, 75 RedirectURL: c.RedirectURIs[0], 76 Scopes: scope, 77 Endpoint: oauth2.Endpoint{ 78 AuthURL: c.AuthURI, 79 TokenURL: c.TokenURI, 80 }, 81 }, nil 82} 83 84// JWTConfigFromJSON uses a Google Developers service account JSON key file to read 85// the credentials that authorize and authenticate the requests. 86// Create a service account on "Credentials" for your project at 87// https://console.developers.google.com to download a JSON key file. 88func JWTConfigFromJSON(jsonKey []byte, scope ...string) (*jwt.Config, error) { 89 var f credentialsFile 90 if err := json.Unmarshal(jsonKey, &f); err != nil { 91 return nil, err 92 } 93 if f.Type != serviceAccountKey { 94 return nil, fmt.Errorf("google: read JWT from JSON credentials: 'type' field is %q (expected %q)", f.Type, serviceAccountKey) 95 } 96 scope = append([]string(nil), scope...) // copy 97 return f.jwtConfig(scope), nil 98} 99 100// JSON key file types. 101const ( 102 serviceAccountKey = "service_account" 103 userCredentialsKey = "authorized_user" 104) 105 106// credentialsFile is the unmarshalled representation of a credentials file. 107type credentialsFile struct { 108 Type string `json:"type"` // serviceAccountKey or userCredentialsKey 109 110 // Service Account fields 111 ClientEmail string `json:"client_email"` 112 PrivateKeyID string `json:"private_key_id"` 113 PrivateKey string `json:"private_key"` 114 TokenURL string `json:"token_uri"` 115 ProjectID string `json:"project_id"` 116 117 // User Credential fields 118 // (These typically come from gcloud auth.) 119 ClientSecret string `json:"client_secret"` 120 ClientID string `json:"client_id"` 121 RefreshToken string `json:"refresh_token"` 122} 123 124func (f *credentialsFile) jwtConfig(scopes []string) *jwt.Config { 125 cfg := &jwt.Config{ 126 Email: f.ClientEmail, 127 PrivateKey: []byte(f.PrivateKey), 128 PrivateKeyID: f.PrivateKeyID, 129 Scopes: scopes, 130 TokenURL: f.TokenURL, 131 } 132 if cfg.TokenURL == "" { 133 cfg.TokenURL = JWTTokenURL 134 } 135 return cfg 136} 137 138func (f *credentialsFile) tokenSource(ctx context.Context, scopes []string) (oauth2.TokenSource, error) { 139 switch f.Type { 140 case serviceAccountKey: 141 cfg := f.jwtConfig(scopes) 142 return cfg.TokenSource(ctx), nil 143 case userCredentialsKey: 144 cfg := &oauth2.Config{ 145 ClientID: f.ClientID, 146 ClientSecret: f.ClientSecret, 147 Scopes: scopes, 148 Endpoint: Endpoint, 149 } 150 tok := &oauth2.Token{RefreshToken: f.RefreshToken} 151 return cfg.TokenSource(ctx, tok), nil 152 case "": 153 return nil, errors.New("missing 'type' field in credentials") 154 default: 155 return nil, fmt.Errorf("unknown credential type: %q", f.Type) 156 } 157} 158 159// ComputeTokenSource returns a token source that fetches access tokens 160// from Google Compute Engine (GCE)'s metadata server. It's only valid to use 161// this token source if your program is running on a GCE instance. 162// If no account is specified, "default" is used. 163// Further information about retrieving access tokens from the GCE metadata 164// server can be found at https://cloud.google.com/compute/docs/authentication. 165func ComputeTokenSource(account string) oauth2.TokenSource { 166 return oauth2.ReuseTokenSource(nil, computeSource{account: account}) 167} 168 169type computeSource struct { 170 account string 171} 172 173func (cs computeSource) Token() (*oauth2.Token, error) { 174 if !metadata.OnGCE() { 175 return nil, errors.New("oauth2/google: can't get a token from the metadata service; not running on GCE") 176 } 177 acct := cs.account 178 if acct == "" { 179 acct = "default" 180 } 181 tokenJSON, err := metadata.Get("instance/service-accounts/" + acct + "/token") 182 if err != nil { 183 return nil, err 184 } 185 var res struct { 186 AccessToken string `json:"access_token"` 187 ExpiresInSec int `json:"expires_in"` 188 TokenType string `json:"token_type"` 189 } 190 err = json.NewDecoder(strings.NewReader(tokenJSON)).Decode(&res) 191 if err != nil { 192 return nil, fmt.Errorf("oauth2/google: invalid token JSON from metadata: %v", err) 193 } 194 if res.ExpiresInSec == 0 || res.AccessToken == "" { 195 return nil, fmt.Errorf("oauth2/google: incomplete token received from metadata") 196 } 197 return &oauth2.Token{ 198 AccessToken: res.AccessToken, 199 TokenType: res.TokenType, 200 Expiry: time.Now().Add(time.Duration(res.ExpiresInSec) * time.Second), 201 }, nil 202} 203