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.
 
 
 

142 lines
4.6 KiB

  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 clientcredentials
  5. import (
  6. "context"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "net/http/httptest"
  11. "net/url"
  12. "testing"
  13. "golang.org/x/oauth2/internal"
  14. )
  15. func newConf(serverURL string) *Config {
  16. return &Config{
  17. ClientID: "CLIENT_ID",
  18. ClientSecret: "CLIENT_SECRET",
  19. Scopes: []string{"scope1", "scope2"},
  20. TokenURL: serverURL + "/token",
  21. EndpointParams: url.Values{"audience": {"audience1"}},
  22. }
  23. }
  24. type mockTransport struct {
  25. rt func(req *http.Request) (resp *http.Response, err error)
  26. }
  27. func (t *mockTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
  28. return t.rt(req)
  29. }
  30. func TestTokenSourceGrantTypeOverride(t *testing.T) {
  31. wantGrantType := "password"
  32. var gotGrantType string
  33. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  34. body, err := ioutil.ReadAll(r.Body)
  35. if err != nil {
  36. t.Errorf("ioutil.ReadAll(r.Body) == %v, %v, want _, <nil>", body, err)
  37. }
  38. if err := r.Body.Close(); err != nil {
  39. t.Errorf("r.Body.Close() == %v, want <nil>", err)
  40. }
  41. values, err := url.ParseQuery(string(body))
  42. if err != nil {
  43. t.Errorf("url.ParseQuery(%q) == %v, %v, want _, <nil>", body, values, err)
  44. }
  45. gotGrantType = values.Get("grant_type")
  46. w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
  47. w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&token_type=bearer"))
  48. }))
  49. config := &Config{
  50. ClientID: "CLIENT_ID",
  51. ClientSecret: "CLIENT_SECRET",
  52. Scopes: []string{"scope"},
  53. TokenURL: ts.URL + "/token",
  54. EndpointParams: url.Values{
  55. "grant_type": {wantGrantType},
  56. },
  57. }
  58. token, err := config.TokenSource(context.Background()).Token()
  59. if err != nil {
  60. t.Errorf("config.TokenSource(_).Token() == %v, %v, want !<nil>, <nil>", token, err)
  61. }
  62. if gotGrantType != wantGrantType {
  63. t.Errorf("grant_type == %q, want %q", gotGrantType, wantGrantType)
  64. }
  65. }
  66. func TestTokenRequest(t *testing.T) {
  67. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  68. if r.URL.String() != "/token" {
  69. t.Errorf("authenticate client request URL = %q; want %q", r.URL, "/token")
  70. }
  71. headerAuth := r.Header.Get("Authorization")
  72. if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" {
  73. t.Errorf("Unexpected authorization header, %v is found.", headerAuth)
  74. }
  75. if got, want := r.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; got != want {
  76. t.Errorf("Content-Type header = %q; want %q", got, want)
  77. }
  78. body, err := ioutil.ReadAll(r.Body)
  79. if err != nil {
  80. r.Body.Close()
  81. }
  82. if err != nil {
  83. t.Errorf("failed reading request body: %s.", err)
  84. }
  85. if string(body) != "audience=audience1&grant_type=client_credentials&scope=scope1+scope2" {
  86. t.Errorf("payload = %q; want %q", string(body), "grant_type=client_credentials&scope=scope1+scope2")
  87. }
  88. w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
  89. w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&token_type=bearer"))
  90. }))
  91. defer ts.Close()
  92. conf := newConf(ts.URL)
  93. tok, err := conf.Token(context.Background())
  94. if err != nil {
  95. t.Error(err)
  96. }
  97. if !tok.Valid() {
  98. t.Fatalf("token invalid. got: %#v", tok)
  99. }
  100. if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" {
  101. t.Errorf("Access token = %q; want %q", tok.AccessToken, "90d64460d14870c08c81352a05dedd3465940a7c")
  102. }
  103. if tok.TokenType != "bearer" {
  104. t.Errorf("token type = %q; want %q", tok.TokenType, "bearer")
  105. }
  106. }
  107. func TestTokenRefreshRequest(t *testing.T) {
  108. internal.ResetAuthCache()
  109. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  110. if r.URL.String() == "/somethingelse" {
  111. return
  112. }
  113. if r.URL.String() != "/token" {
  114. t.Errorf("Unexpected token refresh request URL: %q", r.URL)
  115. }
  116. headerContentType := r.Header.Get("Content-Type")
  117. if got, want := headerContentType, "application/x-www-form-urlencoded"; got != want {
  118. t.Errorf("Content-Type = %q; want %q", got, want)
  119. }
  120. body, _ := ioutil.ReadAll(r.Body)
  121. const want = "audience=audience1&grant_type=client_credentials&scope=scope1+scope2"
  122. if string(body) != want {
  123. t.Errorf("Unexpected refresh token payload.\n got: %s\nwant: %s\n", body, want)
  124. }
  125. w.Header().Set("Content-Type", "application/json")
  126. io.WriteString(w, `{"access_token": "foo", "refresh_token": "bar"}`)
  127. }))
  128. defer ts.Close()
  129. conf := newConf(ts.URL)
  130. c := conf.Client(context.Background())
  131. c.Get(ts.URL + "/somethingelse")
  132. }