17370845950

Facebook OAuth 2.0 认证集成:Go 语言完整实践指南

本文详解如何使用 `golang.org/x/oauth2` 和官方 facebook 适配器(`golang.org/x/oauth2/facebook`)实现安全、合规的 facebook 登录流程,涵盖授权码获取、令牌交换、用户信息拉取及常见错误规避。

在 Go 中集成 Facebook OAuth 2.0 认证时,一个典型误区是手动拼接 /oauth/access_token 请求 URL 并重复使用授权码(code)——这正是你遇到 "This authorization code has been used" 错误的根本原因。Facebook 的 OAuth 流程要求:每个 code 仅能被 POST 到 https://graph.facebook.com/oauth/access_token 一次,且必须通过 application/x-www-form-urlencoded 方式提交(含 client_id、client_secret、redirect_uri 和 code),而非 GET 请求。而你代码中既用 NewTransportFromCode()(已内部完成令牌交换),又额外发起 GET 请求,导致 code 被重复消费。

✅ 正确做法是:统一使用 oauth2.Config.Exchange() 方法完成令牌交换,它会自动构造符合规范的 POST 请求,并妥善处理响应。同时,应优先使用 golang.org/x/oauth2/facebook 提供的预配置 Endpoint,避免手动指定不兼容的授权/令牌端点(如旧版 dialog/oauth)。

以下是精简、可运行的完整示例(Go 1.18+):

package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
    "net/url"
    "strings"

    "golang.org/x/oauth2"
    "golang.org/x/oauth2/facebook"
)

var (
    // 替换为你的 Facebook App 配置
    oauthConf = &oauth2.Config{
        ClientID:     "YOUR_FACEBOOK_APP_ID",
        ClientSecret: "YOUR_FACEBOOK_APP_SECRET",
        RedirectURL:  "http://localhost:9090/oauth2callback",
        Scopes:       []string{"public_profile", "email"},
        Endpoint:     facebook.Endpoint, // ✅ 使用官方预设端点,无需手动指定
    }
    oauthStateString = "random_state_string_123456" // 防 CSRF,务必每次登录生成唯一值(生产环境建议用 crypto/rand)
)

func handleMain(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    fmt.Fprint(w, `
        

Facebook OAuth Demo

Login with Facebook `) } func handleFacebookLogin(w http.ResponseWriter, r *http.Request) { // ✅ 构造标准授权 URL(state 参数必须传递) url := oauthConf.AuthCodeURL(oauthStateString, oauth2.AccessTypeOnline) http.Redirect(w, r, url, http.StatusTemporaryRedirect) } func handleFacebookCallback(w http.ResponseWriter, r *http.Request) { // ? 校验 state 防止 CSRF 攻击 state := r.FormValue("state") if state != oauthStateString { http.Error(w, "invalid state", http.StatusBadRequest) return } code := r.FormValue("code") if code == "" { http.Error(w, "code not found", http.StatusBadRequest) return } // ✅ 唯一正确方式:调用 Exchange 获取 token token, err := oauthConf.Exchange(r.Context(), code) // 注意:r.Context() 替代已废弃的 oauth2.NoContext if err != nil { log.Printf("Exchange failed: %v", err) http.Error(w, "Failed to exchange code for token", http.StatusInternalServerError) return } // ✅ 使用 access_token 调用 Graph API client := oauthConf.Client(r.Context(), token) resp, err := client.Get("https://graph.facebook.com/me?fields=id,name,email,picture.width(200)") if err != nil { log.Printf("API request failed: %v", err) http.Error(w, "Failed to fetch user data", http.StatusInternalServerError) return } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { log.Printf("Read response body failed: %v", err) http.Error(w, "Failed to read response", http.StatusInternalServerError) return } log.Printf("User info: %s", string(body)) fmt.Fprintf(w, "Success! User data: %s", string(body)) } func main() { http.HandleFunc("/", handleMain) http.HandleFunc("/login", handleFacebookLogin) http.HandleFunc("/oauth2callback", handleFacebookCallback) log.Println("Server starting on :9090") log.Fatal(http.ListenAndServe(":9090", nil)) }

? 关键注意事项

  • 禁止手动构造 /oauth/access_token 请求:oauth2.Config.Exchange() 已封装全部逻辑(包括 POST、表单编码、错误解析),自行拼接极易出错。
  • state 参数不可或缺:必须在 AuthCodeURL() 和回调中严格校验,防止跨站请求伪造(CSRF)。
  • RedirectURL 必须完全一致:需与 Facebook App 后台设置的「Valid OAuth Redirect URIs」精确匹配(含协议、端口、路径)。
  • 使用 r.Context():oauth2.NoContext 已弃用,应传入 r.Context() 以支持超时和取消。
  • 生产环境增强:oauthStateString 应动态生成(如 crypto/rand),并绑定 session;Token 应持久化存储(如数据库);API 响应需结构化解析(推荐 json.Unmarshal)。

遵循此模式,即可稳定、安全地完成 Facebook OAuth 集成,彻底规避“authorization code has been used”等典型错误。