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