Google Drive API Go快速入门授权失败问题求助
解决Google Drive API Go版授权时"invalid_grant" "Malformed auth code"问题
核心问题分析
你的Python版本正常说明凭证本身没问题,问题出在Go语言oauth2流程和回调地址的匹配上:
- 无端口的
http://localhost回调地址可能导致Google授权服务器返回的授权码与本地程序验证时的回调地址不匹配 fmt.Scan(&authCode)可能无法正确读取完整授权码(比如意外截断或保留多余空白字符)
具体解决步骤
1. 修正credentials.json中的回调地址
将redirect_uris修改为Google推荐的离线回调地址,适配命令行程序场景:
"redirect_uris": ["urn:ietf:wg:oauth:2.0:oob"]
该地址无需本地服务器,授权完成后会直接在浏览器页面显示授权码,彻底避免端口跳转问题。
2. 替换授权码读取逻辑
fmt.Scan会以空白字符作为分隔符,可能导致读取不完整的授权码,改用整行读取并清理空白:
import ( "bufio" "os" "strings" "log" "context" "golang.org/x/oauth2" ) // ... 其他初始化代码 authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline) fmt.Printf("Go to the following link in your browser then copy the authorization code:\n%v\n", authURL) reader := bufio.NewReader(os.Stdin) authCode, err := reader.ReadString('\n') if err != nil { log.Fatalf("Unable to read authorization code: %v", err) } // 移除换行、空格等多余字符 authCode = strings.TrimSpace(authCode) tok, err := config.Exchange(context.TODO(), authCode) if err != nil { log.Fatalf("Unable to retrieve token from web: %v", err) }
3. 验证配置一致性
确保加载到oauth2.Config中的RedirectURL与credentials.json里的redirect_uris完全一致,修改credentials.json后需重启程序重新加载配置。
额外排查点
- 复制授权码时不要包含页面上的多余文本(如"复制"按钮提示、换行符)
- 若坚持使用带端口的
http://localhost:8080,需在本地启动简单HTTP服务器接收回调,可参考Google Go快速入门的完整示例逻辑(但urn:ietf:wg:oauth:2.0:oob更适合命令行场景)
内容的提问来源于stack exchange,提问作者user3117405
相关产品推荐
相关产品推荐

