clientauth.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Copyright 2020 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 externalaccount
  5. import (
  6. "encoding/base64"
  7. "net/http"
  8. "net/url"
  9. "golang.org/x/oauth2"
  10. )
  11. // clientAuthentication represents an OAuth client ID and secret and the mechanism for passing these credentials as stated in rfc6749#2.3.1.
  12. type clientAuthentication struct {
  13. // AuthStyle can be either basic or request-body
  14. AuthStyle oauth2.AuthStyle
  15. ClientID string
  16. ClientSecret string
  17. }
  18. // InjectAuthentication is used to add authentication to a Secure Token Service exchange
  19. // request. It modifies either the passed url.Values or http.Header depending on the desired
  20. // authentication format.
  21. func (c *clientAuthentication) InjectAuthentication(values url.Values, headers http.Header) {
  22. if c.ClientID == "" || c.ClientSecret == "" || values == nil || headers == nil {
  23. return
  24. }
  25. switch c.AuthStyle {
  26. case oauth2.AuthStyleInHeader: // AuthStyleInHeader corresponds to basic authentication as defined in rfc7617#2
  27. plainHeader := c.ClientID + ":" + c.ClientSecret
  28. headers.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(plainHeader)))
  29. case oauth2.AuthStyleInParams: // AuthStyleInParams corresponds to request-body authentication with ClientID and ClientSecret in the message body.
  30. values.Set("client_id", c.ClientID)
  31. values.Set("client_secret", c.ClientSecret)
  32. case oauth2.AuthStyleAutoDetect:
  33. values.Set("client_id", c.ClientID)
  34. values.Set("client_secret", c.ClientSecret)
  35. default:
  36. values.Set("client_id", c.ClientID)
  37. values.Set("client_secret", c.ClientSecret)
  38. }
  39. }