1 回答
TA贡献1847条经验 获得超11个赞
我可以通过添加一个处理程序来解决它
var (
conf *oauth2.Config
)
func GoogleCallbackHandler(w http.ResponseWriter, r *http.Request) {
conf=&oauth2.Config{
ClientID:"700740834863-m4om9r91htn19htq2b6a05fu6vu4j7i5.apps.googleusercontent.com",
ClientSecret:"...-rB",
RedirectURL:"http://localhost:3000/auth/google/callback",
Scopes:[]string{"profile"},
Endpoint:google.Endpoint,
}
http.Redirect(w, r, conf.AuthCodeURL("state"), http.StatusMovedPermanently)
}
func GoogleLoginHandler(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
token, err := conf.Exchange(oauth2.NoContext, code)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
client := conf.Client(oauth2.NoContext, token)
resp, err := client.Get("https://www.googleapis.com/userinfo/v2/me")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
raw, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var profile map[string]interface{}
if err := json.Unmarshal(raw, &profile); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
session, _ := util.GlobalSessions.SessionStart(w, r)
defer session.SessionRelease(w)
session.Set("id_token", token.Extra("id_token"))
session.Set("access_token", token.AccessToken)
session.Set("profile", profile)
http.Redirect(w, r, "/user", http.StatusMovedPermanently)
}
- 1 回答
- 0 关注
- 196 浏览
添加回答
举报