【问题标题】:Error: invalid_request Missing required parameter: client_id in golang错误:invalid_request 缺少必需参数:golang 中的 client_id
【发布时间】:2017-12-09 12:15:18
【问题描述】:

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

我从谷歌开发者控制台获得了客户端 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)
    }

但我从谷歌得到这个错误:

  1. 这是一个错误。

错误:invalid_request

缺少必需参数:client_id

了解更多

请求详情client_id=redirect_uri=http://127.0.0.1:8080/auth response_type=代码 范围=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.emailstate=random

这里有什么问题?我该如何解决?

【问题讨论】:

    标签: go oauth-2.0 google-authentication


    【解决方案1】:

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

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

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

    来自文档:

    一个没有导入的包的初始化方法是为其所有包级变量分配初始值,然后按照它们在源中出现的顺序调用所有 init 函数,可能在多个文件中,如呈现给编译器的那样

    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 程序之前在操作系统级别设置这些 ENV 值。

    【讨论】:

    • 对。那么如何解决呢?
    • 查看我编辑的答案(最后)以获取一些替代修复
    • 抱歉trigger the initialization from the init after you set the values 是什么意思?我将os.Setenv 放入init 中,但这会导致undefined 错误。
    • 我的意思是在“init”函数中执行“googleOauthConfig = ....”。
    • 正如我所说,这导致undefined: googleOauthConfig in googleOauthConfig.AuthCodeURL
    猜你喜欢
    • 2021-11-05
    • 1970-01-01
    • 2021-05-13
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 2022-01-01
    • 1970-01-01
    相关资源
    最近更新 更多