api - 在 golang 中获取 oauth 用户 token 时出现 400 错误?

标签 api go

我试图获取 ebay 用户 token 。 我已经在 ebay 上获得了授权码,但无法获得带有授权码的用户 token 。 代码如下:

status := ctx.UserValue("status").(string)
applicationToken := string(ctx.QueryArgs().Peek("code"))
log.Println("ApplicationToken: ", applicationToken)
log.Println("Status: ", status)
if status == "declined" {
    fmt.Printf("User doesn't give permission. Go back to your dashboard.")
    ctx.Redirect("/dashboard", fasthttp.StatusSeeOther)
}

//var appConfig = config.Config()
client := &http.Client{}

applicationTokenURLEncoded, _ := url.Parse(applicationToken)

body := url.Values{
    "grant_type":   {"authorization_code"},
    "code":         {applicationTokenURLEncoded.String()},
    "redirect_uri": {Runame},
}
reqBody := bytes.NewBufferString(body.Encode())
log.Println("Reqbody: ", reqBody)

req, _ := http.NewRequest("POST", "https://api.sandbox.ebay.com/identity/v1/oauth2/token", reqBody)


authorization := “AppID” + ":" + “CertID”
authorizationBase64 := base64.StdEncoding.EncodeToString([]byte(authorization))

req.Header.Add("Authorization", "Basic "+authorizationBase64)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
log.Println("Body: ", req)

resp, _ := client.Do(req)
log.Println("resp: ", resp)
log.Println("ResBody: ", resp.Body)

错误是这样的:

Bad Request 400

最佳答案

我看起来消息的格式不正确(这就是服务器返回 400 的原因)。

当你设置你的标题时,你写:

req.Header.Add("Authorization", "Basic "+authorizationBase64)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

Golang 有一个很好的内置方法可以将授权添加到 header :SetBasicAuth ,这是http.Request的一个方法。

func (r *Request) SetBasicAuth(username, password string)

SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.

With HTTP Basic Authentication the provided username and password are not encrypted.

因此,您可以尝试以下操作,而不是手动设置授权 header :

req.SetBasicAuth("AppID”, “CertID”)

您使用的是 CertID,但我认为您指的是 ClientIdClientSecret - 分别是用户密码


不知道这是否是您问题的原因:)。一种帮助找出答案的方法是一致的错误检查,请参阅您的行:

applicationTokenURLEncoded, _ := url.Parse(applicationToken)

关于api - 在 golang 中获取 oauth 用户 token 时出现 400 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43720183/

相关文章:

json - 在 Go 中解码不一致的 JSON

go - 最大化 CustomResourceDefinition 可以拥有的 CustomResource 数量 | kubebuilder 和运营商 SDK

python - 访问 betfair API 以获取马匹价格

python-3.x - Dark Sky API 在 Python 3 中每天迭代一年

java - Retrofit 需要太多时间才能得到响应

csv - 如果匹配列值,golang csv 删除重复项

go - 带有空格的POST参数

javascript - Ajax get with jsonp 给出 "SyntaxError: missing ; before statement"错误

javascript - 如何避免在 Angular 4 上多次调用相同的 API?

sql - Gorm Join表查询