func TestFetchTokenLocalCacheMiss(t *testing.T) { m := &mockMemcache{vals: make(tokMap)} memcacheGob = m accessTokenCount = 0 delete(tokens, testScopeKey) // clear local cache f, err := oauth2.New( AppEngineContext(nil), oauth2.Scope(testScope), ) if err != nil { t.Error(err) } tr := f.NewTransport() c := http.Client{Transport: tr} c.Get("server") if w := 1; m.getCount != w { t.Errorf("bad memcache.Get count: got %v, want %v", m.getCount, w) } if w := 1; accessTokenCount != w { t.Errorf("bad AccessToken count: got %v, want %v", accessTokenCount, w) } if w := 1; m.setCount != w { t.Errorf("bad memcache.Set count: got %v, want %v", m.setCount, w) } // Make sure local cache has been populated _, ok := tokens[testScopeKey] if !ok { t.Errorf("local cache not populated!") } }
func Example_serviceAccounts() { // Your credentials should be obtained from the Google // Developer Console (https://console.developers.google.com). opts, err := oauth2.New( // The contents of your RSA private key or your PEM file // that contains a private key. // If you have a p12 file instead, you // can use `openssl` to export the private key into a pem file. // // $ openssl pkcs12 -in key.p12 -out key.pem -nodes // // It only supports PEM containers with no passphrase. oauth2.JWTClient( "*****@*****.**", []byte("-----BEGIN RSA PRIVATE KEY-----...")), oauth2.Scope( "https://www.googleapis.com/auth/bigquery", "https://www.googleapis.com/auth/blogger", ), google.JWTEndpoint(), // If you would like to impersonate a user, you can // create a transport with a subject. The following GET // request will be made on the behalf of [email protected]. // Subject is optional. oauth2.Subject("*****@*****.**"), ) if err != nil { log.Fatal(err) } // Initiate an http.Client, the following GET request will be // authorized and authenticated on the behalf of [email protected]. client := http.Client{Transport: opts.NewTransport()} client.Get("...") }
func Example_webServer() { // Your credentials should be obtained from the Google // Developer Console (https://console.developers.google.com). opts, err := oauth2.New( oauth2.Client("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET"), oauth2.RedirectURL("YOUR_REDIRECT_URL"), oauth2.Scope( "https://www.googleapis.com/auth/bigquery", "https://www.googleapis.com/auth/blogger", ), google.Endpoint(), ) if err != nil { log.Fatal(err) } // Redirect user to Google's consent page to ask for permission // for the scopes specified above. url := opts.AuthCodeURL("state", "online", "auto") fmt.Printf("Visit the URL for the auth dialog: %v", url) // Handle the exchange code to initiate a transport t, err := opts.NewTransportFromCode("exchange-code") if err != nil { log.Fatal(err) } client := http.Client{Transport: t} client.Get("...") }
// NewOAuth2Provider returns a generic OAuth 2.0 backend endpoint. func NewOAuth2Provider(opts []oauth2.Option) martini.Handler { f, err := oauth2.New(opts...) if err != nil { // TODO(jbd): Don't panic. panic(fmt.Sprintf("oauth2: %s", err)) } return func(s sessions.Session, c martini.Context, w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { switch r.URL.Path { case PathLogin: login(f, s, w, r) case PathLogout: logout(s, w, r) case PathCallback: handleOAuth2Callback(f, s, w, r) } } tk := unmarshallToken(s) if tk != nil { // check if the access token is expired if tk.Expired() && tk.Refresh() == "" { s.Delete(keyToken) tk = nil } } // Inject tokens. c.MapTo(tk, (*Tokens)(nil)) } }
func Example_computeEngine() { opts, err := oauth2.New( // Query Google Compute Engine's metadata server to retrieve // an access token for the provided account. // If no account is specified, "default" is used. google.ComputeEngineAccount(""), ) if err != nil { log.Fatal(err) } client := http.Client{Transport: opts.NewTransport()} client.Get("...") }
func Example_appEngine() { ctx := appengine.NewContext(nil) opts, err := oauth2.New( google.AppEngineContext(ctx), oauth2.Scope( "https://www.googleapis.com/auth/bigquery", "https://www.googleapis.com/auth/blogger", ), ) if err != nil { log.Fatal(err) } // The following client will be authorized by the App Engine // app's service account for the provided scopes. client := http.Client{Transport: opts.NewTransport()} client.Get("...") }
func TestFetchTokenLocalCacheExpired(t *testing.T) { m := &mockMemcache{vals: make(tokMap)} memcacheGob = m accessTokenCount = 0 // Pre-populate the local cache tokens[testScopeKey] = &oauth2.Token{ AccessToken: "mytoken", Expiry: time.Now().Add(-1 * time.Hour), } // Pre-populate the memcache tok := &oauth2.Token{ AccessToken: "mytoken", Expiry: time.Now().Add(1 * time.Hour), } m.Set(nil, &memcache.Item{ Key: testScopeKey, Object: *tok, Expiration: 1 * time.Hour, }) m.setCount = 0 f, err := oauth2.New( AppEngineContext(nil), oauth2.Scope(testScope), ) if err != nil { t.Error(err) } c := http.Client{Transport: f.NewTransport()} c.Get("server") if w := 1; m.getCount != w { t.Errorf("bad memcache.Get count: got %v, want %v", m.getCount, w) } if w := 0; accessTokenCount != w { t.Errorf("bad AccessToken count: got %v, want %v", accessTokenCount, w) } if w := 0; m.setCount != w { t.Errorf("bad memcache.Set count: got %v, want %v", m.setCount, w) } // Make sure local cache remains populated _, ok := tokens[testScopeKey] if !ok { t.Errorf("local cache not populated!") } }
func Example_serviceAccountsJSON() { // Your credentials should be obtained from the Google // Developer Console (https://console.developers.google.com). // Navigate to your project, then see the "Credentials" page // under "APIs & Auth". // To create a service account client, click "Create new Client ID", // select "Service Account", and click "Create Client ID". A JSON // key file will then be downloaded to your computer. opts, err := oauth2.New( google.ServiceAccountJSONKey("/path/to/your-project-key.json"), oauth2.Scope( "https://www.googleapis.com/auth/bigquery", "https://www.googleapis.com/auth/blogger", ), ) if err != nil { log.Fatal(err) } // Initiate an http.Client. The following GET request will be // authorized and authenticated on the behalf of // your service account. client := http.Client{Transport: opts.NewTransport()} client.Get("...") }