【问题标题】:How to add query params to google oauth in golang?如何在golang中向google oauth添加查询参数?
【发布时间】:2016-09-22 12:21:20
【问题描述】:

在我的用例中,我必须向 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。有人可以对此提出一些建议吗?

【问题讨论】:

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


    【解决方案1】:

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

    hostDomainOption := oauth2.SetAuthURLParam("hd", "example.com")
    
    authUrl := oAuthConfig.AuthCodeURL("state",
        oauth2.AccessTypeOffline,
        hostDomainOption)
    

    我认为您可能遇到的问题是注意到 AuthCodeURL 方法是 variadic

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      相关资源
      最近更新 更多