在我的用例中,我必须向Google oauth重定向URL添加查询参数。我正在添加一个关键字为redirect
的查询参数。我正在尝试以以下方式添加,
var (
googleRedirectURL = "http://127.0.0.1:8080/oauth-callback/google"
oauthCfg = &oauth2.Config{
ClientID: "XXXXXXXXXX",
ClientSecret: "XXXXXXXXXX",
Endpoint: google.Endpoint,
RedirectURL: "http://127.0.0.1:8080/oauth-callback/google",
Scopes: []string{"https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"},
}
//random string for oauth2 API calls to protect against CSRF
googleOauthStateString = getUUID()
)
const profileInfoURL = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json"
func HandleGoogleLogin(w http.ResponseWriter, r *http.Request) {
redirect := strings.TrimSpace(r.FormValue("redirect"))
if redirect == "" {
httpErrorf(w, "HandleGoogleLogin() :: Missing redirect value for /login")
return
}
q := url.Values{
"redirect": {redirect},
}.Encode()
//params := '{"redirect": '+redirect+'}'
log.Printf("HandleGoogleLogin() :: redirect %s ", q)
//param := oauth2.SetAuthURLParam("redirect", q)
// url := oauthCfg.AuthCodeURL("state", param)
//append the redirect URL to the request
oauthCfg.RedirectURL = googleRedirectURL
url := oauthCfg.AuthCodeURL("state")
url = oauthCfg.AuthCodeURL(googleOauthStateString, oauth2.AccessTypeOnline)
url = url + "?redirct=" + q
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
但这会将重定向参数附加到url的状态参数。因此,当我比较状态码
oauthCfg.AuthCodeURL("state")
时,值会有所不同。我的意思是以下检查。state := r.FormValue("state")
log.Printf("HandleGoogleCallback() :: state string %s ", state)
if state != googleOauthStateString {
log.Printf("invalid oauth state, expected '%s', got '%s'\n", googleOauthStateString, state)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
我可以使用
?
分隔符拆分字符串以获取状态值。但是我认为必须有一种添加查询参数的标准方法来重定向google oauth中的url。有人可以对此提出一些建议吗? 最佳答案
我想你很亲密。这对我有用:
hostDomainOption := oauth2.SetAuthURLParam("hd", "example.com")
authUrl := oAuthConfig.AuthCodeURL("state",
oauth2.AccessTypeOffline,
hostDomainOption)
我认为您可能被困的地方注意到AuthCodeURL方法是variadic。
关于redirect - 如何在Golang中将查询参数添加到Google OAuth?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36513674/