Error: invalid_request Missing required parameter: client_id in golang

Error: invalid_request Missing required parameter: client_id in golang

我在使用 Google OAuth2 进行身份验证时遇到困难。

我从 google 开发者控制台获得了客户端 ID 和密码,我想出了这个代码:

package main

    import (
        "fmt"
        "golang.org/x/oauth2"
        "golang.org/x/oauth2/google"
        "io/ioutil"
        "net/http"
        "os"
    )

    const htmlIndex = `<html><body>
    <a href="/GoogleLogin">Log in with Google</a>
    </body></html>
    `

    func init() {
        // Setup Google's example test keys
        os.Setenv("CLIENT_ID", "somrestring-otherstring.apps.googleusercontent.com")
        os.Setenv("SECRET_KEY", "alongcharachterjumble")
    }

    var (
        googleOauthConfig = &oauth2.Config{
            RedirectURL:  "http://127.0.0.1:8080/auth",  //defined in Google console
            ClientID:     os.Getenv("CLIENT_ID"),
            ClientSecret: os.Getenv("SECRET_KEY"),
            Scopes: []string{"https://www.googleapis.com/auth/userinfo.profile",
                "https://www.googleapis.com/auth/userinfo.email"},
            Endpoint: google.Endpoint,
        }
        // Some random string, random for each request
        oauthStateString = "random"
    )

    func main() {
        http.HandleFunc("/", handleMain)
        http.HandleFunc("/GoogleLogin", handleGoogleLogin)
        http.HandleFunc("/GoogleCallback", handleGoogleCallback)
        fmt.Println(http.ListenAndServe(":8080", nil))
    }

    func handleMain(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, htmlIndex)
        fmt.Println("another request made")
    }

    func handleGoogleLogin(w http.ResponseWriter, r *http.Request) {
        url := googleOauthConfig.AuthCodeURL(oauthStateString)
        http.Redirect(w, r, url, http.StatusTemporaryRedirect)
    }

    func handleGoogleCallback(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 := googleOauthConfig.Exchange(oauth2.NoContext, code)
        if err != nil {
            fmt.Println("Code exchange failed with '%s'\n", err)
            http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
            return
        }

        response, err := http.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token.AccessToken)

        defer response.Body.Close()
        contents, err := ioutil.ReadAll(response.Body)
        fmt.Fprintf(w, "Content: %s\n", contents)
    }

但是我从 google 得到这个错误:

  1. That’s an error.

Error: invalid_request

Missing required parameter: client_id

Learn more

Request Details client_id= redirect_uri=http://127.0.0.1:8080/auth response_type=code scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email state=random

这是怎么回事?我该如何解决?

错误信息表明ClientID没有初始化。

这看起来与代码一致,因为 var 声明在 init 函数之前执行。

因此,当您的 var 请求 os.Getenv("CLIENT_ID") 时,该值为空白,因为 init 尚未执行。

来自文档:

A package with no imports is initialized by assigning initial values to all its package-level variables followed by calling all init functions in the order they appear in the source, possibly in multiple files, as presented to the compiler

https://golang.org/ref/spec#Package_initialization

要解决此问题,请将字符串直接放入 var 初始化,或者在设置值后从 init 触发初始化。

喜欢:

var (
    googleOauthConfig *oauth2.Config
)

func init() {
     // init ENV
     // initialize the variable using ENV values
     googleOauthConfig = &oauth2.Config{ ... }
}

或者,您可以在执行实际的 Go 程序之前在 OS 级别设置那些 ENV 值。