Skip to content

Instantly share code, notes, and snippets.

@border
Created September 1, 2012 16:32
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save border/3579615 to your computer and use it in GitHub Desktop.
Save border/3579615 to your computer and use it in GitHub Desktop.
Google goauth2 example
package main
import (
"code.google.com/p/goauth2/oauth"
"crypto/tls"
"io/ioutil"
"log"
"net/http"
"text/template"
)
var notAuthenticatedTemplate = template.Must(template.New("").Parse(`
<html><body>
You have currently not given permissions to access your data. Please authenticate this app with the Google OAuth provider.
<form action="/authorize" method="POST"><input type="submit" value="Ok, authorize this app with my id"/></form>
</body></html>
`))
var userInfoTemplate = template.Must(template.New("").Parse(`
<html><body>
This app is now authenticated to access your Google user info. Your details are:<br />
{{.}}
</body></html>
`))
// variables used during oauth protocol flow of authentication
var (
code = ""
token = ""
)
var oauthCfg = &oauth.Config{
//TODO: put your project's Client Id here. To be got from https://code.google.com/apis/console
ClientId: "531571078206.apps.googleusercontent.com",
//TODO: put your project's Client Secret value here https://code.google.com/apis/console
ClientSecret: "jgZSS8pDBKQb8Mzm4gB0XnJ1",
//For Google's oauth2 authentication, use this defined URL
AuthURL: "https://accounts.google.com/o/oauth2/auth",
//For Google's oauth2 authentication, use this defined URL
TokenURL: "https://accounts.google.com/o/oauth2/token",
//To return your oauth2 code, Google will redirect the browser to this page that you have defined
//TODO: This exact URL should also be added in your Google API console for this project within "API Access"->"Redirect URIs"
RedirectURL: "http://127.0.0.1:8080/oauth2callback",
//This is the 'scope' of the data that you are asking the user's permission to access. For getting user's info, this is the url that Google has defined.
Scope: "https://www.googleapis.com/auth/userinfo.profile",
}
//This is the URL that Google has defined so that an authenticated application may obtain the user's info in json format
const profileInfoURL = "https://www.googleapis.com/auth2/v1/userinfo"
const port = ":8080"
func main() {
http.HandleFunc("/", handleRoot)
http.HandleFunc("/authorize", handleAuthorize)
//Google will redirect to this page to return your code, so handle it appropriately
http.HandleFunc("/oauth2callback", handleOAuth2Callback)
log.Println("Listen On: " + port)
http.ListenAndServe(port, nil)
}
func handleRoot(w http.ResponseWriter, r *http.Request) {
notAuthenticatedTemplate.Execute(w, nil)
}
// Start the authorization process
func handleAuthorize(w http.ResponseWriter, r *http.Request) {
//Get the Google URL which shows the Authentication page to the user
url := oauthCfg.AuthCodeURL("")
//redirect user to that page
http.Redirect(w, r, url, http.StatusFound)
}
// Function that handles the callback from the Google server
func handleOAuth2Callback(w http.ResponseWriter, r *http.Request) {
//Get the code from the response
code := r.FormValue("code")
t := &oauth.Transport{oauth.Config: oauthCfg}
// Exchange the received code for a token
tok, _ := t.Exchange(code)
{
tokenCache := oauth.CacheFile("./request.token")
err := tokenCache.PutToken(tok)
if err != nil {
log.Fatal("Cache write:", err)
}
log.Printf("Token is cached in %v\n", tokenCache)
}
// Skip TLS Verify
t.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
// Make the request.
req, err := t.Client().Get(profileInfoURL)
if err != nil {
log.Fatal("Request Error:", err)
}
defer req.Body.Close()
body, _ := ioutil.ReadAll(req.Body)
log.Println(string(body))
userInfoTemplate.Execute(w, string(body))
}
@aries1980
Copy link

With Go 1.2, I get ./goauth2-example.go:86: unknown oauth.Transport field 'oauth.Config' in struct literal

@kyledinh
Copy link

kyledinh commented Apr 8, 2014

^^ I came across the same issue.

Remove the "oauth." to:
t := &oauth.Transport{ Config: oauthCfg }

Copy link

ghost commented Jul 18, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment