本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

210 lines
6.6KB

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