import (
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
var (
googleOauthConfig *oauth2.Config
oauthStateString = "random_string"
)
func init() {
googleOauthConfig = &oauth2.Config{
RedirectURL: "http://localhost:8080/oauth2callback",
ClientID: "" ,
ClientSecret: "" ,
Scopes: []string{"https://www.googleapis.com/auth/userinfo.profile"},
Endpoint: google.Endpoint,
}
}
func HandleHome(w http.ResponseWriter, r *http.Request) {
var html = `
Google Login
`
fmt.Fprintf(w, html, GetLoginURL(oauthStateString))
}
func GetLoginURL(state string) string {
return googleOauthConfig.AuthCodeURL(state)
}
func HandleOAuth2Callback(w http.ResponseWriter, r *http.Request) {
state := r.FormValue("state")
if state != oauthStateString {
fmt.Printf("invalid OAuth state, expected '%s', got '%s'\n", oauthStateString, state)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
code := r.FormValue("code")
token, err := googleOauthConfig.Exchange(oauth2.NoContext, code)
if err != nil {
fmt.Printf("oauth2: %s", err.Error())
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
client := googleOauthConfig.Client(oauth2.NoContext, token)
resp, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")
if err != nil {
fmt.Printf("Get: %s", err.Error())
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("ReadAll: %s", err.Error())
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
fmt.Fprintf(w, "Content: %s\n", contents)
}
http.HandleFunc("/", HandleHome)
http.HandleFunc("/oauth2callback", HandleOAuth2Callback)
http.ListenAndServe(":8080", nil)
var (
googleOauthConfig *oauth2.Config
)
func init() {
googleOauthConfig = &oauth2.Config{
ClientID: "" ,
ClientSecret: "" ,
RedirectURL: "http://localhost:9000/oauth2callback",
Scopes: []string{
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
},
Endpoint: google.Endpoint,
}
}
func HandleGoogleLogin(w http.ResponseWriter, r *http.Request) {
url := googleOauthConfig.AuthCodeURL("state")
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func HandleGoogleCallback(w http.ResponseWriter, r *http.Request) {
code := r.FormValue("code")
token, err := googleOauthConfig.Exchange(oauth2.NoContext, code)
if err != nil {
fmt.Fprintln(w, err)
return
}
client := googleOauthConfig.Client(oauth2.NoContext, token)
resp, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")
if err != nil {
fmt.Fprintln(w, err)
return
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
fmt.Fprintf(w, "Content: %s\n", contents)
}
启动客户端:
http.HandleFunc("/login/google", HandleGoogleLogin)
http.HandleFunc("/oauth2callback", HandleGoogleCallback)
log.Fatal(http.ListenAndServe(":9000", nil))