Skip to content

Commit 5501212

Browse files
committed
Merge branch 'readme'
2 parents de1f5a3 + 45a1111 commit 5501212

File tree

5 files changed

+267
-79
lines changed

5 files changed

+267
-79
lines changed

Diff for: README.md

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# OAuth2 for Go
2+
3+
oauth2 package contains a client implementation for OAuth 2.0 spec.
4+
5+
## Installation
6+
7+
~~~~
8+
go get github.com/golang/oauth2
9+
~~~~
10+
11+
See [godoc](http://godoc.org/github.com/golang/oauth2) for further documentation and examples.
12+
13+
## Contributing
14+
15+
Fork the repo, make changes, run the tests and open a pull request.
16+
17+
Before we can accept any pull requests
18+
we have to jump through a couple of legal hurdles,
19+
primarily a Contributor License Agreement (CLA):
20+
21+
- **If you are an individual writing original source code**
22+
and you're sure you own the intellectual property,
23+
then you'll need to sign an [individual CLA](http://code.google.com/legal/individual-cla-v1.0.html).
24+
- **If you work for a company that wants to allow you to contribute your work**,
25+
then you'll need to sign a [corporate CLA](http://code.google.com/legal/corporate-cla-v1.0.html).
26+
27+
You can sign these electronically (just scroll to the bottom).
28+
After that, we'll be able to accept your pull requests.

Diff for: example_test.go

+112
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
package oauth2_test
2+
3+
import (
4+
"fmt"
5+
"log"
6+
"net/http"
7+
"testing"
8+
9+
"github.com/golang/oauth2"
10+
)
11+
12+
// TODO(jbd): Remove after Go 1.4.
13+
// Related to https://codereview.appspot.com/107320046
14+
func TestA(t *testing.T) {}
15+
16+
func Example_config() {
17+
conf, err := oauth2.NewConfig(&oauth2.Options{
18+
ClientID: "YOUR_CLIENT_ID",
19+
ClientSecret: "YOUR_CLIENT_SECRET",
20+
RedirectURL: "YOUR_REDIRECT_URL",
21+
Scopes: []string{"SCOPE1", "SCOPE2"},
22+
},
23+
"https://provider.com/o/oauth2/auth",
24+
"https://provider.com/o/oauth2/token")
25+
if err != nil {
26+
log.Fatal(err)
27+
}
28+
29+
// Redirect user to consent page to ask for permission
30+
// for the scopes specified above.
31+
url, err := conf.AuthCodeURL("")
32+
if err != nil {
33+
log.Fatal(err)
34+
}
35+
fmt.Printf("Visit the URL for the auth dialog: %v", url)
36+
37+
// Use the exchange code that is handled by the redirect URL.
38+
// NewTransportWithCode will do the handshake to retrieve
39+
// an access token and iniate a Transport that is
40+
// authorized and authenticated the retrieved token.
41+
var exchangeCode string
42+
if _, err = fmt.Scan(&exchangeCode); err != nil {
43+
log.Fatal(err)
44+
}
45+
t, err := conf.NewTransportWithCode(exchangeCode)
46+
if err != nil {
47+
log.Fatal(err)
48+
}
49+
50+
// You can use t to initiate a new http.Client and
51+
// start making authenticated requests.
52+
client := http.Client{Transport: t}
53+
client.Get("...")
54+
55+
// Alternatively, you can initiate a new transport
56+
// with tokens from a cache.
57+
cache := oauth2.NewFileCache("/path/to/file")
58+
// NewTransportWithCache will try to read the cached
59+
// token, if any error occurs, it returns the error.
60+
// If a token is available at the cache, initiates
61+
// a new transport authorized and authenticated with
62+
// the read token. If token expires, and a new access
63+
// token is retrieved, it writes the newly fetched
64+
// token to the cache.
65+
t, err = conf.NewTransportWithCache(cache)
66+
if err != nil {
67+
log.Fatal(err)
68+
}
69+
client = http.Client{Transport: t}
70+
client.Get("...")
71+
}
72+
73+
func Example_jWTConfig() {
74+
conf, err := oauth2.NewJWTConfig(&oauth2.JWTOptions{
75+
76+
// The path to the pem file. If you have a p12 file instead, you
77+
// can use `openssl` to export the private key into a pem file.
78+
// $ openssl pkcs12 -in key.p12 -out key.pem -nodes
79+
PemFilename: "/path/to/pem/file.pem",
80+
Scopes: []string{"SCOPE1", "SCOPE2"},
81+
},
82+
"https://provider.com/o/oauth2/token")
83+
if err != nil {
84+
log.Fatal(err)
85+
}
86+
87+
// Initiate an http.Client, the following GET request will be
88+
// authorized and authenticated on the behalf of
89+
90+
client := http.Client{Transport: conf.NewTransport()}
91+
client.Get("...")
92+
93+
// If you would like to impersonate a user, you can
94+
// create a transport with a subject. The following GET
95+
// request will be made on the behalf of [email protected].
96+
client = http.Client{Transport: conf.NewTransportWithUser("[email protected]")}
97+
client.Get("...")
98+
99+
// Alternatively you can iniate a transport with
100+
// a token read from the cache.
101+
// If the existing access token expires, and a new access token is
102+
// retrieved, the newly fetched token will be written to the cache.
103+
cache := oauth2.NewFileCache("/path/to/file")
104+
t, err := conf.NewTransportWithCache(cache)
105+
if err != nil {
106+
log.Fatal(err)
107+
}
108+
client = http.Client{Transport: t}
109+
// The following request will be authorized by the token
110+
// retrieved from the cache.
111+
client.Get("...")
112+
}

Diff for: google/example_test.go

+127
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
package google_test
2+
3+
import (
4+
"fmt"
5+
"log"
6+
"net/http"
7+
"testing"
8+
9+
"github.com/golang/oauth2"
10+
"github.com/golang/oauth2/google"
11+
"google.golang.org/appengine"
12+
)
13+
14+
// Remove after Go 1.4.
15+
// Related to https://codereview.appspot.com/107320046
16+
func TestA(t *testing.T) {}
17+
18+
func Example_webServer() {
19+
// Your credentials should be obtained from the Google
20+
// Developer Console (https://console.developers.google.com).
21+
config, err := google.NewConfig(&oauth2.Options{
22+
ClientID: "YOUR_CLIENT_ID",
23+
ClientSecret: "YOUR_CLIENT_SECRET",
24+
RedirectURL: "YOUR_REDIRECT_URL",
25+
Scopes: []string{
26+
"https://www.googleapis.com/auth/bigquery",
27+
"https://www.googleapis.com/auth/blogger"},
28+
})
29+
if err != nil {
30+
log.Fatal(err)
31+
}
32+
33+
// Redirect user to Google's consent page to ask for permission
34+
// for the scopes specified above.
35+
url, err := config.AuthCodeURL("")
36+
if err != nil {
37+
log.Fatal(err)
38+
}
39+
fmt.Printf("Visit the URL for the auth dialog: %v", url)
40+
41+
// Handle the exchange code to initiate a transport
42+
t, err := config.NewTransportWithCode("exchange-code")
43+
if err != nil {
44+
log.Fatal(err)
45+
}
46+
client := http.Client{Transport: t}
47+
client.Get("...")
48+
49+
// Alternatively you can initiate a new transport
50+
// with a token from a cache.
51+
cache := oauth2.NewFileCache("/path/to/file")
52+
// NewTransportWithCache will try to read the cached
53+
// token, if any error occurs, it returns the error.
54+
// If a token is available at the cache, initiates
55+
// a new transport authorized and authenticated with
56+
// the read token. If token expires, and a new access
57+
// token is retrieved, it writes the newly fetched
58+
// token to the cache.
59+
t, err = config.NewTransportWithCache(cache)
60+
if err != nil {
61+
log.Fatal(err)
62+
}
63+
client = http.Client{Transport: t}
64+
client.Get("...")
65+
}
66+
67+
func Example_serviceAccounts() {
68+
// Your credentials should be obtained from the Google
69+
// Developer Console (https://console.developers.google.com).
70+
config, err := google.NewServiceAccountConfig(&oauth2.JWTOptions{
71+
72+
// The path to the pem file. If you have a p12 file instead, you
73+
// can use `openssl` to export the private key into a pem file.
74+
// $ openssl pkcs12 -in key.p12 -out key.pem -nodes
75+
PemFilename: "/path/to/pem/file.pem",
76+
Scopes: []string{
77+
"https://www.googleapis.com/auth/bigquery",
78+
},
79+
})
80+
if err != nil {
81+
log.Fatal(err)
82+
}
83+
84+
// Initiate an http.Client, the following GET request will be
85+
// authorized and authenticated on the behalf of
86+
87+
client := http.Client{Transport: config.NewTransport()}
88+
client.Get("...")
89+
90+
// If you would like to impersonate a user, you can
91+
// create a transport with a subject. The following GET
92+
// request will be made on the behalf of [email protected].
93+
client = http.Client{Transport: config.NewTransportWithUser("[email protected]")}
94+
client.Get("...")
95+
96+
// Alternatively you can iniate a transport with
97+
// a token read from the cache.
98+
// If the existing access token expires, and a new access token is
99+
// retrieved, the newly fetched token will be written to the cache.
100+
cache := oauth2.NewFileCache("/path/to/file")
101+
t, err := config.NewTransportWithCache(cache)
102+
if err != nil {
103+
log.Fatal(err)
104+
}
105+
client = http.Client{Transport: t}
106+
// The following request will be authorized by the token
107+
// retrieved from the cache.
108+
client.Get("...")
109+
}
110+
111+
func Example_appEngine() {
112+
context := appengine.NewContext(nil)
113+
config := google.NewAppEngineConfig(context, []string{
114+
"https://www.googleapis.com/auth/bigquery",
115+
})
116+
// The following client will be authorized by the App Engine
117+
// app's service account for the provided scopes.
118+
client := http.Client{Transport: config.NewTransport()}
119+
client.Get("...")
120+
}
121+
122+
func Example_computeEngine() {
123+
// If no other account is specified, "default" is used.
124+
config := google.NewComputeEngineConfig("")
125+
client := http.Client{Transport: config.NewTransport()}
126+
client.Get("...")
127+
}

Diff for: google/google.go

-53
Original file line numberDiff line numberDiff line change
@@ -11,59 +11,6 @@
1111
//
1212
// For more information, please read
1313
// https://developers.google.com/accounts/docs/OAuth2.
14-
//
15-
// Example usage:
16-
// // Web server flow usage:
17-
// // Specify your configuration.
18-
// // Your credentials should be obtained from the Google
19-
// // Developer Console (https://console.developers.google.com).
20-
// var config = google.NewConfig(&oauth2.Opts{
21-
// ClientID: YOUR_CLIENT_ID,
22-
// ClientSecret: YOUR_CLIENT_SECRET,
23-
// RedirectURL: "http://you.example.org/handler",
24-
// Scopes: []string{ "scope1", "scope2" },
25-
// })
26-
//
27-
// // A landing page redirects to Google to get the auth code.
28-
// func landing(w http.ResponseWriter, r *http.Request) {
29-
// http.Redirect(w, r, config.AuthCodeURL(""), http.StatusFound)
30-
// }
31-
//
32-
// // The user will be redirected back to this handler, that takes the
33-
// // "code" query parameter and Exchanges it for an access token.
34-
// func handler(w http.ResponseWriter, r *http.Request) {
35-
// t, err := config.NewTransportWithCode(r.FormValue("code"))
36-
// // The Transport now has a valid Token. Create an *http.Client
37-
// // with which we can make authenticated API requests.
38-
// c := t.Client()
39-
// c.Post(...)
40-
// }
41-
//
42-
// // Service accounts usage:
43-
// // Google Developer Console will provide a p12 file contains
44-
// // a private key. You need to export it to the pem format.
45-
// // Run the following command to generate a pem file that
46-
// // contains your private key:
47-
// // $ openssl pkcs12 -in /path/to/p12key.p12 -out key.pem -nodes
48-
// // Then, specify your configuration.
49-
// var config = google.NewServiceAccountConfig(&oauth2.JWTOpts{
50-
// Email: "[email protected]",
51-
// PemFilename: "/path/to/key.pem",
52-
// Scopes: []string{
53-
// "https://www.googleapis.com/auth/drive.readonly"
54-
// },
55-
// })
56-
//
57-
// // Create a transport.
58-
// t, err := config.NewTransport()
59-
// // Or, you can create a transport that impersonates
60-
// // a Google user.
61-
// t, err := config.NewTransportWithUser(googleUserEmail)
62-
//
63-
// // Create a client to make authorized requests.
64-
// c := t.Client()
65-
// c.Post(...)
66-
//
6714
package google
6815

6916
import (

Diff for: oauth2.go

-26
Original file line numberDiff line numberDiff line change
@@ -5,32 +5,6 @@
55
// Package oauth2 provides support for making
66
// OAuth2 authorized and authenticated HTTP requests.
77
// It can additionally grant authorization with Bearer JWT.
8-
//
9-
// Example usage:
10-
//
11-
// // Specify your configuration. (typically as a global variable)
12-
// config := oauth2.NewConfig(&oauth2.Options{
13-
// ClientID: YOUR_CLIENT_ID,
14-
// ClientSecret: YOUR_CLIENT_SECRET,
15-
// RedirectURL: "http://you.example.org/handler",
16-
// Scopes: []string{ "scope1", "scope2" },
17-
// }, OAUTH2_PROVIDER_AUTH_URL, OAUTH2_PROVIDER_TOKEN_URL)
18-
//
19-
// // A landing page redirects to the OAuth provider to get the auth code.
20-
// func landing(w http.ResponseWriter, r *http.Request) {
21-
// http.Redirect(w, r, config.AuthCodeURL("foo"), http.StatusFound)
22-
// }
23-
//
24-
// // The user will be redirected back to this handler, that takes the
25-
// // "code" query parameter and Exchanges it for an access token.
26-
// func handler(w http.ResponseWriter, r *http.Request) {
27-
// t, err := config.NewTransportWithCode(r.FormValue("code"))
28-
// // The Transport now has a valid Token. Create an *http.Client
29-
// // with which we can make authenticated API requests.
30-
// c := t.Client()
31-
// c.Post(...)
32-
// }
33-
//
348
package oauth2
359

3610
import (

0 commit comments

Comments
 (0)