google.go 6.4 KB

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