以下 App Engine 处理程序在我可以获得令牌的范围内工作:
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 获取令牌响应并愉快地显示它。但是,最好不必将用户重定向到 example.com/?state=SOME_UNIQUE_VALUE&code=AQB0iYpAf8nMmX5blahblah# =以实现登录。
有没有办法使用 client.Get 等访问授权 URL,遵循重定向,从生成的查询字符串中获取代码并将其填充到字符串中以供处理程序使用?不用求助于阿贾克斯,就是这样。