func tokenFromWeb(g_config *oauth.Config) *oauth.Token { ch := make(chan string) randState := fmt.Sprintf("st%d", time.Now()) var listener *net.TCPListener go serveCallback(listener, randState, ch) defer listener.Close() g_config.RedirectURL = "http://localhost:8080/callback" authUrl := g_config.AuthCodeURL(randState) go openUrl(authUrl) log.Printf("Authorize this app at: %s", authUrl) code := <-ch log.Printf("Got code: %s", code) t := &oauth.Transport{ Config: g_config, Transport: condDebugTransport(http.DefaultTransport), } _, err := t.Exchange(code) if err != nil { log.Fatalf("Token exchange error: %v", err) } return t.Token }
// Handle register the passed http.HandleFunc to be executed when // a request matches path. The HandleFunc will receive the oauth2 // code corresponding to the passed oauth.Config as form values. func HandleFunc(path string, h http.HandlerFunc, cfg *oauth.Config) error { mutex.Lock() defer mutex.Unlock() u, err := url.Parse(cfg.RedirectURL) if err != nil { return fmt.Errorf("bad redirect URL: %v", err) } if u.Path != CallbackPath { return fmt.Errorf("RedirectURL has to point to %q, it points to %q", CallbackPath, u.Path) } handlers[path] = h rh := http.RedirectHandler(cfg.AuthCodeURL(path), http.StatusFound) http.Handle(path, rh) return nil }
func authRefreshToken(c *oauth.Config) (*oauth.Token, error) { l, err := net.Listen("tcp", "localhost:8016") defer l.Close() if err != nil { return nil, err } open.Run(c.AuthCodeURL("")) var token *oauth.Token done := make(chan struct{}) f := func(w http.ResponseWriter, r *http.Request) { code := r.FormValue("code") transport := &oauth.Transport{Config: c} token, err = transport.Exchange(code) done <- struct{}{} } go http.Serve(l, http.HandlerFunc(f)) <-done return token, err }
func tokenFromWeb(g_config *oauth.Config) *oauth.Token { ch := make(chan string) randState := fmt.Sprintf("st%d", time.Now()) ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { if req.URL.Path == "/favicon.ico" { http.Error(rw, "", 404) return } if req.FormValue("state") != randState { log.Printf("State doesn't match: req = %#v", req) http.Error(rw, "", 500) return } if code := req.FormValue("code"); code != "" { fmt.Fprintf(rw, "<h1>Success</h1>Authorized.") rw.(http.Flusher).Flush() ch <- code return } log.Printf("no code") http.Error(rw, "", 500) })) defer ts.Close() g_config.RedirectURL = ts.URL fmt.Println(ts.URL) authUrl := g_config.AuthCodeURL(randState) go openUrl(authUrl) log.Printf("Authorize this app at: %s", authUrl) code := <-ch log.Printf("Got code: %s", code) t := &oauth.Transport{ Config: g_config, Transport: condDebugTransport(http.DefaultTransport), } _, err := t.Exchange(code) if err != nil { log.Fatalf("Token exchange error: %v", err) } return t.Token }
// buildOAuthHTTPClient takes the user through the three-legged OAuth flow. Opens a browser in the native OS or // outputs a URL, blocking until the redirect completes to the /oauth2callback URI. // Returns an instance of an HTTP client that can be passed to the constructor of the YouTube client. func buildOAuthHTTPClient(config *oauth.Config) (*http.Client, error) { transport := &oauth.Transport{Config: config} // Try to read the token from the cache file. // If there's an error, the token is invalid or doesn't exist, do the 3-legged OAuth flow. token, err := config.TokenCache.Token() if err != nil { // Make a channel for the web server to communicate with us on to tell us we have a code codeChannel := make(chan string) // Start web server. This is how this program receives the authorization code when the browser redirects. err := startWebServer(codeChannel) if err != nil { return nil, err } // Open url in browser url := config.AuthCodeURL("") err = openUrl(url) if err != nil { fmt.Println("Visit the URL below to get a code. This program will pause until the site is visted.") } else { fmt.Println("Your browser has been opened to an authorization URL. This program will resume once authorization has been provided.\n") } fmt.Println(url) // Block, wait for the web server to get the code back code := <-codeChannel // This will take care of caching the code on the local filesystem, if necessary, as long as the TokenCache // attribute in the config is set token, err = transport.Exchange(code) if err != nil { return nil, err } } transport.Token = token return transport.Client(), nil }
// RunFlowWithTransport runs through a 3LO OAuth 2.0 flow to get credentials for // Google Storage using the specified HTTP transport. func RunFlowWithTransport(config *oauth.Config, transport http.RoundTripper) (*http.Client, error) { if config == nil { config = DefaultOAuthConfig("") } oauthTransport := &oauth.Transport{ Config: config, Transport: transport, } if _, err := config.TokenCache.Token(); err != nil { url := config.AuthCodeURL("") fmt.Printf(`Your browser has been opened to visit: %s Enter the verification code:`, url) var code string fmt.Scan(&code) if _, err := oauthTransport.Exchange(code); err != nil { return nil, fmt.Errorf("Failed exchange: %s", err) } } return oauthTransport.Client(), nil }
func tokenFromWeb(config *oauth.Config) *oauth.Token { randState := fmt.Sprintf("st%d", time.Now().UnixNano()) config.RedirectURL = RedirectURI authURL := config.AuthCodeURL(randState) log.Info("Opening auth URL in browser.") log.Info(authURL) log.Info("If the URL doesn't open please open it manually and copy the code here.") openURL(authURL) code := getCodeFromStdin() log.Infof("Got code: %s", code) t := &oauth.Transport{ Config: config, Transport: http.DefaultTransport, } _, err := t.Exchange(code) if err != nil { log.Fatalf("Token exchange error: %v", err) } return t.Token }
func tokenFromWeb(config *oauth.Config) *oauth.Token { ch := make(chan string) randState := fmt.Sprintf("st%d", time.Now().UnixNano()) http.HandleFunc("/auth", func(rw http.ResponseWriter, req *http.Request) { if req.FormValue("state") != randState { log.Printf("State doesn't match: req = %#v", req) http.Error(rw, "", 500) return } if code := req.FormValue("code"); code != "" { fmt.Fprintf(rw, "<h1>Success</h1>Authorized.") rw.(http.Flusher).Flush() ch <- code return } log.Printf("no code") http.Error(rw, "", 500) }) config.RedirectURL = fmt.Sprintf("http://localhost:%s/auth", *port) authUrl := config.AuthCodeURL(randState) go openUrl(authUrl) log.Printf("Authorize this app at: %s", authUrl) code := <-ch log.Printf("Got code: %s", code) t := &oauth.Transport{ Config: config, Transport: http.DefaultTransport, } _, err := t.Exchange(code) if err != nil { log.Fatalf("Token exchange error: %v", err) } return t.Token }
// Get auth code from user func promptUserForAuthCode(config *oauth.Config) string { authUrl := config.AuthCodeURL("state") fmt.Println("Go to the following link in your browser:") fmt.Printf("%v\n\n", authUrl) return util.Prompt("Enter verification code: ") }