gpt4 book ai didi

google-app-engine - 在没有 http.Redirect 的情况下实现 OAuth2 Facebook 登录

转载 作者:IT王子 更新时间:2023-10-29 00:44:25 26 4
gpt4 key购买 nike

以下 App Engine 处理程序在我可以获得 token 的范围内工作:

func home(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)

oaConfig := map [string]string {
"ClientID": "(redacted)",
"ClientSecret": "(redacted)",
"Scope": "email",
"AuthURL": "https://graph.facebook.com/oauth/authorize",
"TokenURL": "https://graph.facebook.com/oauth/access_token",
"RedirectURL": "http://www.example.com/",
}

code := r.FormValue("code")
if code == "" {
// 1. Code request
url := oaConfig["AuthURL"] +
"?client_id=" + oaConfig["ClientID"] +
"&redirect_uri=" + oaConfig["RedirectURL"] +
"&state=SOME_UNIQUE_VALUE"
http.Redirect(w, r, url, http.StatusFound)
}

// 2. Token request
client := urlfetch.Client(c)
tokenResponse, err := client.PostForm(oaConfig["TokenURL"],
url.Values{
"client_id": {oaConfig["ClientID"]},
"redirect_uri": {oaConfig["RedirectURL"]},
"client_secret": {oaConfig["ClientSecret"]},
"code": {code},
})

if err != nil {
// ...
} else {
// 3. Read token from response body
defer tokenResponse.Body.Close()
body, err := ioutil.ReadAll(tokenResponse.Body)
if err != nil {
// ...
} else {
token := string(body)
}
}

// ...
}

当连接到模板时,它会从 Facebook 获取 token 响应并愉快地显示它。但是,最好不必将用户重定向到 example.com/?state=SOME_UNIQUE_VALUE&code=AQB0iYpAf8nMmX5blahblah#= 以实现登录。

有没有办法使用 client.Get 等访问授权 URL,跟随重定向,从结果查询字符串中获取代码并将其填充到字符串中以供处理程序使用?也就是说,无需求助于 Ajax。

最佳答案

Is there a way to use client.Get etc to visit the authorise URL, follow the redirect, obtain the code from the resulting query string and stuff it into a string for use by the handler?

不,因为用户可能必须将他们的登录凭据输入到 Facebook(如果他们是第一次使用,可能还需要连接到你的应用程序)——如果你从你的服务器上完成这一切,那几乎不可能完成而不向用户显示。

如果您想在现有用户登录 Facebook 时识别他们重新访问您的应用程序,则只能在客户端完成。 JS SDK 中的 FB.getLoginStatus 能够为您做到这一点——它会识别用户,同时为他们提供有效的访问 token 。

关于google-app-engine - 在没有 http.Redirect 的情况下实现 OAuth2 Facebook 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13897425/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com