goalng oauth2:无法获取令牌:" client_id不能为空"

时间:2017-08-28 21:18:34

标签: go oauth-2.0

我正在进行OAuth2身份验证,以下是代码段,

import (
    "context"
    "fmt"
    "net/http"
    "golang.org/x/oauth2"
)

var (
    ctx  context.Context
    conf = &oauth2.Config{
        RedirectURL:  "http://localhost:3001/ApiCallback",
        ClientID:     "C1c179367105720f145aecefa4fafdd587f3",
        ClientSecret: "ff3abcfad5acfe03ff64e9ca56c636e72b12",
        Scopes:       []string{"all"},
        Endpoint: oauth2.Endpoint{AuthURL: "https://api.example.com/v1/authorize",
            TokenURL: "https://api.example.com/v1/access_token",
        },
    }
    url = conf.AuthCodeURL("state", oauth2.AccessTypeOnline)
)

func main() {

    ctx = context.Background()
    http.HandleFunc("/", handler)
    http.HandleFunc("/ApiLogin", handleOAuthAPILogin)
    http.HandleFunc("/ApiCallback", handleAPICallback)
    fmt.Println(http.ListenAndServe(":3001", nil))

    fmt.Printf("Visit the URL for the auth dialog: %v", url)
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func handleOAuthAPILogin(w http.ResponseWriter, r *http.Request) {
    fmt.Println("Came to Spark Login")
    http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}

func handleAPICallback(w http.ResponseWriter, r *http.Request) {

    fmt.Println("Came to Callback")
    code := r.FormValue("code")

    fmt.Println("Auth Code:", code)
    fmt.Println("Client ID:", conf.ClientID)
    fmt.Println("Client Secret:", conf.ClientSecret)

    token, err := conf.Exchange(ctx, code)
    if err != nil {
        fmt.Println("Code exchange failed with '%s'\n", err)
        http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
    }
    fmt.Println("Token Code:", token)
}

使用上面的代码段, 我可以在登录后获取代码(授权代码),但在交换该代码时失败。它抛出的错误是" client_id"是空的。

我已经验证了我的" conf"对象,存在值。

但它仍然会抛出此错误。任何人都可以帮我解决这个问题

这是输出

$ go run main.go
Came to Spark Login
Came to Callback
Auth Code: YzdjZGZmZTgtYTllYi00zQ1OTI2OTNiZTQtYmQx
Client ID: C1c179367145aecefa4fafdd587f3
Client Secret: ff3abcfad5acfe034b9531ff64e9ca56c636e72b12
Code exchange failed with '%s'
 oauth2: cannot fetch token: 400 Bad Request
Response: {"errorCode":0,"message":"client_id cannot be null","errors":[{"errorCode":0,"description":"client_id cannot be null"}],"trackingId":"NA_3ca9eb7e-f3ce-406
2-8c29-7030ea9b1a08"}

0 个答案:

没有答案