2016-04-17 29 views
3

進行身份驗證我想弄清楚如何使用包golang.org/x/oauth2在一個支持oauth2的站點上進行身份驗證。用oauth2使用軟件包「golang.org/x/oauth2」

我寫了下面的作品的代碼,我只是好奇,如果這是正確的做法,用這種特定的庫,獲得* http.Client:

func handleCallback(w http.ResponseWriter, r *http.Request) { 
    state := r.FormValue("state") 
    if state != oauthStateString { 
     fmt.Printf("invalid oauth state, expected '%s', got '%s'\n", oauthStateString, state) 
     http.Redirect(w, r, "/", http.StatusTemporaryRedirect) 
     return 
    } 

    code := r.FormValue("code") 
    token, err := oauthConf.Exchange(oauth2.NoContext, code) 
    if err != nil { 
     fmt.Printf("oauthConf.Exchange() failed with '%s'\n", err) 
     http.Redirect(w, r, "/", http.StatusTemporaryRedirect) 
     return 
    } 

    ts := oauth2.StaticTokenSource(
     &oauth2.Token{AccessToken: token.AccessToken}, 
    ) 

    tc := oauth2.NewClient(oauth2.NoContext, ts) // got *http.Client 

回答

1

追問:我用它並調整了幾次,它完成了這項工作。