有几个步骤可以让我更轻松地访问 Google,我会向您展示完整的流程。我的猜测是您被困在第二步,因为您没有将其作为帖子发送。
第 1 步:请求访问权限
https://accounts.google.com/o/oauth2/auth?client_id={clientid}.apps.googleusercontent.com&redirect_uri={From console}&scope=openid%20email&response_type=code
这只是显示要求他们批准您的窗口。用户批准访问后,您将获得一次性验证码。
第 2 步: 将 Authentication Code 交换为 AccessToken 和 RefreshToken。请注意,这需要作为 HTTP POST 而不是 HTTP Get 发送。
https://accounts.google.com/o/oauth2/token
code={Authentication Code from step 1}&client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&redirect_uri=={From console}&grant_type=authorization_code
你应该得到一个看起来像这样的 JSon 字符串。
{
"access_token" : "ya29.1.AADtN_VSBMC2Ga2lhxsTKjVQ_ROco8VbD6h01aj4PcKHLm6qvHbNtn-_BIzXMw",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "1/J-3zPA8XR1o_cXebV9sDKn_f5MTqaFhKFxH-3PUPiJ4"
}
现在您可以使用 Access_token 并使用它来提出您的请求。但是访问令牌只能使用 1 小时,然后它们会在此之前过期,您需要使用 Refresh_token 来获取新的访问令牌。此外,如果您要再次访问您的用户数据,您应该将 refresh_token 保存在某个位置,以便您始终可以访问那里的数据。
第 3 步:使用 Refreshtoken
https://accounts.google.com/o/oauth2/token
client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&refresh_token={RefreshToken from step 2}&grant_type=refresh_token
这一次您只会取回访问令牌,因为您的 refreshtoken 是好的,直到用户删除身份验证或您已经 6 个月没有使用它。
{
"access_token" : "ya29.1.AADtN_XK16As2ZHlScqOxGtntIlevNcasMSPwGiE3pe5ANZfrmJTcsI3ZtAjv4sDrPDRnQ",
"token_type" : "Bearer",
"expires_in" : 3600
}
您可以在这里找到更多详细信息Google 3 Legged oauth2 flow