Skip to content

Instantly share code, notes, and snippets.

@campoy
Last active December 16, 2015 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save campoy/5483266 to your computer and use it in GitHub Desktop.
Save campoy/5483266 to your computer and use it in GitHub Desktop.
Small sample app on using goauth2
// Short example showing how to get an oauth2 token using a .pem key and how the token should be added
// to the http requests.
package main
import (
"fmt"
"io/ioutil"
"net/http"
"code.google.com/p/goauth2/oauth/jwt"
)
type AuthorizedTransport struct {
Token string
APIKey string
Transport http.RoundTripper
}
func (t *AuthorizedTransport) RoundTrip(q *http.Request) (*http.Response, error) {
q.Header.Set("Authorization", "OAuth "+t.Token)
args := q.URL.Query()
args.Add("key", t.APIKey)
q.URL.RawQuery = args.Encode()
r, err := t.Transport.RoundTrip(q)
return r, err
}
// newAuthClient creates an http.Client with OAuth2 authentication.
// key should be the contents of a .pem file, if you have a .p12 key and want to
// convert it to .pem use:
// $ openssl pkcs12 -passin pass:notasecret -in key.p12 -out key.pem -nocerts -nodes
func newAuthClient(email, scope string, key []byte, apiKey string) (*http.Client, error) {
o, err := jwt.NewToken(email, scope, key).Assert(http.DefaultClient)
if err != nil {
return nil, fmt.Errorf("creating auth client: %v", err)
}
return &http.Client{Transport: &AuthorizedTransport{o.AccessToken, apiKey, http.DefaultTransport}}, nil
}
func main() {
key, err := ioutil.ReadFile("key.pem")
if err != nil {
panic(err)
}
c, err := newAuthClient("campoy@google.com", "https://www.googleapis.com/auth/taskqueue", key, "APIKEY")
if err != nil {
panic(err)
}
// Authenticated GET request
res, err := c.Get("www.securedpage.com")
if err != nil {
panic(err)
}
fmt.Println(res)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment