【问题标题】:google OAUTH2 exchange authorization code for acces token "invalid request"访问令牌“无效请求”的谷歌 OAUTH2 交换授权码
【发布时间】:2015-03-30 18:32:06
【问题描述】:

我正在从我的服务器上的这个页面获取 google api 授权代码

https://github.com/google/google-api-php-client/blob/master/examples/user-example.php

在我的主机上测试同一页面

http://mawk3y.net/google/google-api-php-client/examples/user-example.php

在调整客户端 ID、秘密和重定向 uri 之后。

$data =file_get_contents('https://accounts.google.com/o/oauth2/auth?code='.$code.'&client_secret={secret}&redirect_uri={my web page}&grant_type=authorization_code');
print_r($data);

但我收到一个错误,所以我在从该页面获取授权码后尝试将完整的 url 粘贴到浏览器地址栏(与我从该页面获得的相同身份验证码 https://developers.google.com/oauthplayground/

https://accounts.google.com/o/oauth2/token?code={authorization code}&redirect_uri=mywebpage.php&client_id={my client id}&client_secret={secret code}&grant_type=authorization_code

但结果是

{
"error" : "invalid_request"
}

如何解决这个问题并用授权码交换访问令牌

【问题讨论】:

    标签: php google-api authorization access-token


    【解决方案1】:

    您正在将 GET 请求中的参数发送到 authorization 端点 (https://accounts.google.com/o/oauth2/auth),但您必须在 POST 中发送它们em> 对 token 端点 (https://accounts.google.com/o/oauth2/token) 的请求。

    【讨论】:

    • 所有数据都是从 API 控制台复制的相同 uri 以避免错误 [UPDATE] 在问题中添加了我的主机上的测试 url
    • 在仔细检查您的参数/网址后更改了答案
    • 内部文件准备好了 $.post('accounts.google.com/o/oauth2/token?code={code}&client_secret={secret}&redirect_uri={uri}&grant_type=authorization_code').done(function(data){ console.log(data ); }).fail(function(){ console.log('failed'); });结果是“跨源请求被阻止:同源策略不允许在accounts.google.com/o/oauth2/token?code={code}&client_secret={secret}&redirect_uri={redirect uri}&grant_type=authorization_code 读取远程资源。这可以通过将资源移动到相同的域或启用 CORS。令牌“失败”
    • javascript 是从哪里来的?您应该按照原始问题中的建议处理 PHP 中的令牌请求,例如使用 CURL,如此处答案中所述:stackoverflow.com/questions/10932443/…
    • 跟随答案并得到 string(72) "{ "error" : "invalid_grant", "error_description" : "Invalid code." }" 虽然这是我从谷歌得到的授权码我从developers.google.com/oauthplayground 获得的相同代码,正如我所见,因为它已过期或已使用,所以我怎样才能获得新的授权代码
    猜你喜欢
    • 2020-11-20
    • 2015-06-12
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 2018-09-25
    • 2019-06-06
    相关资源
    最近更新 更多