Google OAuth 2.0客户端ID JSON结构与Go结构体不匹配求助
解决Google Cloud Console新格式OAuth客户端ID与Go OAuth2库的兼容问题
问题确认
最近Google Cloud Console针对桌面应用生成的OAuth 2.0客户端ID JSON确实改用了压缩后的短键名格式(比如WCc、Anc这类缩写),而非传统的清晰键名,这直接导致golang.org/x/oauth2包的ConfigFromJSON无法正常解析。
解决方案一:自定义结构体适配新格式
你需要先定义适配新JSON结构的Go结构体,解码后再转换成标准库所需的格式:
package main import ( "encoding/json" "golang.org/x/oauth2" ) // 适配新格式的外层结构体 type NewClientCred struct { WCc struct { ClientID string `json:"client_id"` ProjectID string `json:"project_id"` AuthURI string `json:"Anc"` TokenURI string `json:"hVc"` CertURL string `json:"znc"` ClientSecret string `json:"s2a"` RedirectURIs []string `json:"oNc"` } `json:"WCc"` } // 转换为标准OAuth2 Config func convertToConfig(cred NewClientCred) *oauth2.Config { return &oauth2.Config{ ClientID: cred.WCc.ClientID, ClientSecret: cred.WCc.ClientSecret, RedirectURL: cred.WCc.RedirectURIs[0], // 桌面应用通常只有一个重定向URI Scopes: []string{}, // 根据你的需求添加权限范围 Endpoint: oauth2.Endpoint{ AuthURL: cred.WCc.AuthURI, TokenURL: cred.WCc.TokenURI, }, } } func main() { // 假设jsonData是你下载的JSON字节流 var jsonData []byte = []byte(`{ "WCc": { "client_id": "*****apps.googleusercontent.com", "project_id": "persuasive", "Anc": "https://accounts.google.com/o/oauth2/auth", "hVc": "https://oauth2.googleapis.com/token", "znc": "https://www.googleapis.com/oauth2/v1/certs", "s2a": "GOCSPX-*******", "oNc": ["http://localhost"] } }`) var newCred NewClientCred if err := json.Unmarshal(jsonData, &newCred); err != nil { panic(err) } config := convertToConfig(newCred) // 之后就可以正常使用config进行OAuth2流程了 }
解决方案二:手动转换JSON格式(临时方案)
如果你只是临时使用,可以手动修改下载的JSON文件,将短键名替换为标准键名:
Anc→auth_urihVc→token_uris2a→client_secretoNc→redirect_uris- 去掉外层的
WCc嵌套,直接保留内部的键值对
修改后的JSON示例:
{ "client_id": "*****apps.googleusercontent.com", "project_id": "persuasive", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "client_secret": "GOCSPX-*******", "redirect_uris": ["http://localhost"] }
这样就能直接用ConfigFromJSON解析了,但每次重新生成客户端ID都需要重复操作,适合临时测试。
关于ConfigFromJSON的更新
目前golang.org/x/oauth2官方包的ConfigFromJSON尚未适配这种新格式,暂时没有官方更新版本。你可以选择上述自定义结构体转换的方式,或者关注官方仓库的issue和更新。
内容的提问来源于stack exchange,提问作者xy01
相关产品推荐
相关产品推荐

