无法从 Google 获取访问令牌

时间:2021-07-08 23:52:00

标签: go google-cloud-platform backend access-token

我想获取应用内产品列表,因此在请求时需要“访问令牌”。 但是返回码是400,无效grant_type="password"

id、密码和 oauth2.Config 正在设置中。

  • 去库版本 golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d

代码

  • auth2.go
// PasswordCredentialsToken converts a resource owner username and password
// pair into a token.
//
// Per the RFC, this grant type should only be used "when there is a high
// degree of trust between the resource owner and the client (e.g., the client
// is part of the device operating system or a highly privileged application),
// and when other authorization grant types are not available."
// See https://tools.ietf.org/html/rfc6749#section-4.3 for more info.
//
// The provided context optionally controls which HTTP client is used. See the HTTPClient variable.
func (c *Config) PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error) {
    v := url.Values{
        "grant_type": {"password"},
        "username":   {username},
        "password":   {password},
    }
    if len(c.Scopes) > 0 {
        v.Set("scope", strings.Join(c.Scopes, " "))
    }
    return retrieveToken(ctx, c, v)
}

  • 后端
clientID := os.Getenv("CLIENT_ID")
clientSecretKey := os.Getenv("CLIENT_SECRET_KEY")
id := os.Getenv("GOOGLE_ID")
password := os.Getenv("GOOGLE_PASSWORD")

OAuthConf = &oauth2.Config{
    ClientID:     clientID,
    ClientSecret: clientSecretKey,
    Endpoint:     google.Endpoint,
}

// get token
token, err := OAuthConf.PasswordCredentialsToken(context.Background(), id, password)
if err != nil {
    log.Err.Printf("PasswordCredentialsToken : [%s]\n", err)
    c.Abort()
    return
}
log.Info.Printf("token : [%+v]\n", token)

响应

oauth2: cannot fetch token: 400 Bad Request
Response: {
  "error": "unsupported_grant_type",
  "error_description": "Invalid grant_type: password"
}

0 个答案:

没有答案