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.
 
 
 

90 lines
2.4 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 oauth2_test
  5. import (
  6. "context"
  7. "fmt"
  8. "log"
  9. "net/http"
  10. "time"
  11. "golang.org/x/oauth2"
  12. )
  13. func ExampleConfig() {
  14. ctx := context.Background()
  15. conf := &oauth2.Config{
  16. ClientID: "YOUR_CLIENT_ID",
  17. ClientSecret: "YOUR_CLIENT_SECRET",
  18. Scopes: []string{"SCOPE1", "SCOPE2"},
  19. Endpoint: oauth2.Endpoint{
  20. AuthURL: "https://provider.com/o/oauth2/auth",
  21. TokenURL: "https://provider.com/o/oauth2/token",
  22. },
  23. }
  24. // Redirect user to consent page to ask for permission
  25. // for the scopes specified above.
  26. url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline)
  27. fmt.Printf("Visit the URL for the auth dialog: %v", url)
  28. // Use the authorization code that is pushed to the redirect
  29. // URL. Exchange will do the handshake to retrieve the
  30. // initial access token. The HTTP Client returned by
  31. // conf.Client will refresh the token as necessary.
  32. var code string
  33. if _, err := fmt.Scan(&code); err != nil {
  34. log.Fatal(err)
  35. }
  36. tok, err := conf.Exchange(ctx, code)
  37. if err != nil {
  38. log.Fatal(err)
  39. }
  40. client := conf.Client(ctx, tok)
  41. client.Get("...")
  42. }
  43. func ExampleConfig_customHTTP() {
  44. ctx := context.Background()
  45. conf := &oauth2.Config{
  46. ClientID: "YOUR_CLIENT_ID",
  47. ClientSecret: "YOUR_CLIENT_SECRET",
  48. Scopes: []string{"SCOPE1", "SCOPE2"},
  49. Endpoint: oauth2.Endpoint{
  50. TokenURL: "https://provider.com/o/oauth2/token",
  51. AuthURL: "https://provider.com/o/oauth2/auth",
  52. },
  53. }
  54. // Redirect user to consent page to ask for permission
  55. // for the scopes specified above.
  56. url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline)
  57. fmt.Printf("Visit the URL for the auth dialog: %v", url)
  58. // Use the authorization code that is pushed to the redirect
  59. // URL. Exchange will do the handshake to retrieve the
  60. // initial access token. The HTTP Client returned by
  61. // conf.Client will refresh the token as necessary.
  62. var code string
  63. if _, err := fmt.Scan(&code); err != nil {
  64. log.Fatal(err)
  65. }
  66. // Use the custom HTTP client when requesting a token.
  67. httpClient := &http.Client{Timeout: 2 * time.Second}
  68. ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient)
  69. tok, err := conf.Exchange(ctx, code)
  70. if err != nil {
  71. log.Fatal(err)
  72. }
  73. client := conf.Client(ctx, tok)
  74. _ = client
  75. }