...

Source file src/golang.org/x/oauth2/google/example_test.go

Documentation: golang.org/x/oauth2/google

     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 google_test
     6  
     7  import (
     8  	"context"
     9  	"fmt"
    10  	"io/ioutil"
    11  	"log"
    12  	"net/http"
    13  
    14  	"golang.org/x/oauth2"
    15  	"golang.org/x/oauth2/google"
    16  	"golang.org/x/oauth2/jwt"
    17  )
    18  
    19  func ExampleDefaultClient() {
    20  	client, err := google.DefaultClient(oauth2.NoContext,
    21  		"https://www.googleapis.com/auth/devstorage.full_control")
    22  	if err != nil {
    23  		log.Fatal(err)
    24  	}
    25  	client.Get("...")
    26  }
    27  
    28  func Example_webServer() {
    29  	// Your credentials should be obtained from the Google
    30  	// Developer Console (https://console.developers.google.com).
    31  	conf := &oauth2.Config{
    32  		ClientID:     "YOUR_CLIENT_ID",
    33  		ClientSecret: "YOUR_CLIENT_SECRET",
    34  		RedirectURL:  "YOUR_REDIRECT_URL",
    35  		Scopes: []string{
    36  			"https://www.googleapis.com/auth/bigquery",
    37  			"https://www.googleapis.com/auth/blogger",
    38  		},
    39  		Endpoint: google.Endpoint,
    40  	}
    41  	// Redirect user to Google's consent page to ask for permission
    42  	// for the scopes specified above.
    43  	url := conf.AuthCodeURL("state")
    44  	fmt.Printf("Visit the URL for the auth dialog: %v", url)
    45  
    46  	// Handle the exchange code to initiate a transport.
    47  	tok, err := conf.Exchange(oauth2.NoContext, "authorization-code")
    48  	if err != nil {
    49  		log.Fatal(err)
    50  	}
    51  	client := conf.Client(oauth2.NoContext, tok)
    52  	client.Get("...")
    53  }
    54  
    55  func ExampleJWTConfigFromJSON() {
    56  	// Your credentials should be obtained from the Google
    57  	// Developer Console (https://console.developers.google.com).
    58  	// Navigate to your project, then see the "Credentials" page
    59  	// under "APIs & Auth".
    60  	// To create a service account client, click "Create new Client ID",
    61  	// select "Service Account", and click "Create Client ID". A JSON
    62  	// key file will then be downloaded to your computer.
    63  	data, err := ioutil.ReadFile("/path/to/your-project-key.json")
    64  	if err != nil {
    65  		log.Fatal(err)
    66  	}
    67  	conf, err := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/bigquery")
    68  	if err != nil {
    69  		log.Fatal(err)
    70  	}
    71  	// Initiate an http.Client. The following GET request will be
    72  	// authorized and authenticated on the behalf of
    73  	// your service account.
    74  	client := conf.Client(oauth2.NoContext)
    75  	client.Get("...")
    76  }
    77  
    78  func ExampleSDKConfig() {
    79  	// The credentials will be obtained from the first account that
    80  	// has been authorized with `gcloud auth login`.
    81  	conf, err := google.NewSDKConfig("")
    82  	if err != nil {
    83  		log.Fatal(err)
    84  	}
    85  	// Initiate an http.Client. The following GET request will be
    86  	// authorized and authenticated on the behalf of the SDK user.
    87  	client := conf.Client(oauth2.NoContext)
    88  	client.Get("...")
    89  }
    90  
    91  func Example_serviceAccount() {
    92  	// Your credentials should be obtained from the Google
    93  	// Developer Console (https://console.developers.google.com).
    94  	conf := &jwt.Config{
    95  		Email: "xxx@developer.gserviceaccount.com",
    96  		// The contents of your RSA private key or your PEM file
    97  		// that contains a private key.
    98  		// If you have a p12 file instead, you
    99  		// can use `openssl` to export the private key into a pem file.
   100  		//
   101  		//    $ openssl pkcs12 -in key.p12 -passin pass:notasecret -out key.pem -nodes
   102  		//
   103  		// The field only supports PEM containers with no passphrase.
   104  		// The openssl command will convert p12 keys to passphrase-less PEM containers.
   105  		PrivateKey: []byte("-----BEGIN RSA PRIVATE KEY-----..."),
   106  		Scopes: []string{
   107  			"https://www.googleapis.com/auth/bigquery",
   108  			"https://www.googleapis.com/auth/blogger",
   109  		},
   110  		TokenURL: google.JWTTokenURL,
   111  		// If you would like to impersonate a user, you can
   112  		// create a transport with a subject. The following GET
   113  		// request will be made on the behalf of user@example.com.
   114  		// Optional.
   115  		Subject: "user@example.com",
   116  	}
   117  	// Initiate an http.Client, the following GET request will be
   118  	// authorized and authenticated on the behalf of user@example.com.
   119  	client := conf.Client(oauth2.NoContext)
   120  	client.Get("...")
   121  }
   122  
   123  func ExampleComputeTokenSource() {
   124  	client := &http.Client{
   125  		Transport: &oauth2.Transport{
   126  			// Fetch from Google Compute Engine's metadata server to retrieve
   127  			// an access token for the provided account.
   128  			// If no account is specified, "default" is used.
   129  			// If no scopes are specified, a set of default scopes
   130  			// are automatically granted.
   131  			Source: google.ComputeTokenSource("", "https://www.googleapis.com/auth/bigquery"),
   132  		},
   133  	}
   134  	client.Get("...")
   135  }
   136  
   137  func ExampleCredentialsFromJSON() {
   138  	ctx := context.Background()
   139  	data, err := ioutil.ReadFile("/path/to/key-file.json")
   140  	if err != nil {
   141  		log.Fatal(err)
   142  	}
   143  	creds, err := google.CredentialsFromJSON(ctx, data, "https://www.googleapis.com/auth/bigquery")
   144  	if err != nil {
   145  		log.Fatal(err)
   146  	}
   147  	_ = creds // TODO: Use creds.
   148  }
   149  

View as plain text