如何在Golang中向google oauth添加查询参数?

时间:2016-04-09 06:49:20

标签: redirect go oauth oauth-2.0 google-oauth

在我的用例中,我必须向google oauth重定向网址添加查询参数。我正在添加一个带有密钥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
}

我可以使用?分隔符拆分字符串以获取状态值。但我认为必须有一种标准的方法来添加查询参数来重定向谷歌oauth中的URL。有人可以对此提出一些建议吗?

1 个答案:

答案 0 :(得分:1)

我认为你很接近。这对我有用:

URLComponents

我认为您可能会被卡住的地方注意到AuthCodeURL方法是variadic