oauth.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. /*
  2. *
  3. * Copyright 2015, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. // Package oauth implements gRPC credentials using OAuth.
  34. package oauth
  35. import (
  36. "fmt"
  37. "io/ioutil"
  38. "golang.org/x/net/context"
  39. "golang.org/x/oauth2"
  40. "golang.org/x/oauth2/google"
  41. "golang.org/x/oauth2/jwt"
  42. "google.golang.org/grpc/credentials"
  43. )
  44. // TokenSource supplies PerRPCCredentials from an oauth2.TokenSource.
  45. type TokenSource struct {
  46. oauth2.TokenSource
  47. }
  48. // GetRequestMetadata gets the request metadata as a map from a TokenSource.
  49. func (ts TokenSource) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
  50. token, err := ts.Token()
  51. if err != nil {
  52. return nil, err
  53. }
  54. return map[string]string{
  55. "authorization": token.Type() + " " + token.AccessToken,
  56. }, nil
  57. }
  58. // RequireTransportSecurity indicates whether the credentials requires transport security.
  59. func (ts TokenSource) RequireTransportSecurity() bool {
  60. return true
  61. }
  62. type jwtAccess struct {
  63. jsonKey []byte
  64. }
  65. // NewJWTAccessFromFile creates PerRPCCredentials from the given keyFile.
  66. func NewJWTAccessFromFile(keyFile string) (credentials.PerRPCCredentials, error) {
  67. jsonKey, err := ioutil.ReadFile(keyFile)
  68. if err != nil {
  69. return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err)
  70. }
  71. return NewJWTAccessFromKey(jsonKey)
  72. }
  73. // NewJWTAccessFromKey creates PerRPCCredentials from the given jsonKey.
  74. func NewJWTAccessFromKey(jsonKey []byte) (credentials.PerRPCCredentials, error) {
  75. return jwtAccess{jsonKey}, nil
  76. }
  77. func (j jwtAccess) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
  78. ts, err := google.JWTAccessTokenSourceFromJSON(j.jsonKey, uri[0])
  79. if err != nil {
  80. return nil, err
  81. }
  82. token, err := ts.Token()
  83. if err != nil {
  84. return nil, err
  85. }
  86. return map[string]string{
  87. "authorization": token.TokenType + " " + token.AccessToken,
  88. }, nil
  89. }
  90. func (j jwtAccess) RequireTransportSecurity() bool {
  91. return true
  92. }
  93. // oauthAccess supplies PerRPCCredentials from a given token.
  94. type oauthAccess struct {
  95. token oauth2.Token
  96. }
  97. // NewOauthAccess constructs the PerRPCCredentials using a given token.
  98. func NewOauthAccess(token *oauth2.Token) credentials.PerRPCCredentials {
  99. return oauthAccess{token: *token}
  100. }
  101. func (oa oauthAccess) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
  102. return map[string]string{
  103. "authorization": oa.token.TokenType + " " + oa.token.AccessToken,
  104. }, nil
  105. }
  106. func (oa oauthAccess) RequireTransportSecurity() bool {
  107. return true
  108. }
  109. // NewComputeEngine constructs the PerRPCCredentials that fetches access tokens from
  110. // Google Compute Engine (GCE)'s metadata server. It is only valid to use this
  111. // if your program is running on a GCE instance.
  112. // TODO(dsymonds): Deprecate and remove this.
  113. func NewComputeEngine() credentials.PerRPCCredentials {
  114. return TokenSource{google.ComputeTokenSource("")}
  115. }
  116. // serviceAccount represents PerRPCCredentials via JWT signing key.
  117. type serviceAccount struct {
  118. config *jwt.Config
  119. }
  120. func (s serviceAccount) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
  121. token, err := s.config.TokenSource(ctx).Token()
  122. if err != nil {
  123. return nil, err
  124. }
  125. return map[string]string{
  126. "authorization": token.TokenType + " " + token.AccessToken,
  127. }, nil
  128. }
  129. func (s serviceAccount) RequireTransportSecurity() bool {
  130. return true
  131. }
  132. // NewServiceAccountFromKey constructs the PerRPCCredentials using the JSON key slice
  133. // from a Google Developers service account.
  134. func NewServiceAccountFromKey(jsonKey []byte, scope ...string) (credentials.PerRPCCredentials, error) {
  135. config, err := google.JWTConfigFromJSON(jsonKey, scope...)
  136. if err != nil {
  137. return nil, err
  138. }
  139. return serviceAccount{config: config}, nil
  140. }
  141. // NewServiceAccountFromFile constructs the PerRPCCredentials using the JSON key file
  142. // of a Google Developers service account.
  143. func NewServiceAccountFromFile(keyFile string, scope ...string) (credentials.PerRPCCredentials, error) {
  144. jsonKey, err := ioutil.ReadFile(keyFile)
  145. if err != nil {
  146. return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err)
  147. }
  148. return NewServiceAccountFromKey(jsonKey, scope...)
  149. }
  150. // NewApplicationDefault returns "Application Default Credentials". For more
  151. // detail, see https://developers.google.com/accounts/docs/application-default-credentials.
  152. func NewApplicationDefault(ctx context.Context, scope ...string) (credentials.PerRPCCredentials, error) {
  153. t, err := google.DefaultTokenSource(ctx, scope...)
  154. if err != nil {
  155. return nil, err
  156. }
  157. return TokenSource{t}, nil
  158. }