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