1

我的 Google 登录有问题。我按照服务器端应用程序的 Google 登录中的步骤操作 完成所有这一步之后,我有一个在服务器上运行的 html 文件:

<!DOCTYPE html>
<html itemscope itemtype="http://schema.org/Article">
    <head>
        <link rel="stylesheet" href="theme.css">
        <!-- BEGIN Pre-requisites -->
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>
        <!-- END Pre-requisites -->
        <script>
            function start() {
                gapi.load('auth2', function() {
                    auth2 = gapi.auth2.init({
                        client_id: 'CLIENT_ID'
                    });
                });
            }
        </script>
    </head>
    <body>
        <button id="googleBtn">Connect</button>
        <script>
            $('#googleBtn').click(function() {
                auth2.grantOfflineAccess().then(googleCallback);
            });
        </script>
        <script>
            function googleCallback(authResult) {
                if (authResult['code']) {
                    console.log(authResult);
                } else {
                    console.log(authResult);
                }
            }
        </script>
    </body>
</html>

第一部分工作完美(我认为),当我单击按钮时,弹出一个窗口,我选择一个帐户并获得一个代码。所以现在,我想获取电子邮件和个人资料,所以我在 nodejs 中提出这个请求,用访问令牌交换代码。

var form = {
    code: 'XXXXXXXXXXXX',
    client_id: 'CLIENT_ID,
    client_secret: 'CLIENT',
    grant_type:'authorization_code'
};

var formData = querystring.stringify(form);
var contentLength = formData.length;

request({
    headers: {
      'Content-Length': contentLength,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    uri: 'https://www.googleapis.com/oauth2/v4/token',
    body: formData,
    method: 'POST'
  }, function (err, rep, body) {
    console.log(err);
    console.log(rep.statusCode);
    console.log(body);
  });

但作为回应,我有这个

{
 "error": "redirect_uri_mismatch",
 "error_description": "Bad Request"
}

而且我不明白为什么,因为我没有在 html 文件的主要请求中使用任何 redirect_uri 。我尝试了一些情况,例如在控制台 API 和请求中添加 redirect_uri,但我得到了相同的结果......

你能帮助我吗 ?

4

2 回答 2

7

从客户端auth2.grantOfflineAccess进程中,要在服务器上获取 accessToken,您必须传入redirect_uri=postmessage请求参数。

从你的例子:

var form = {
  code: 'XXXXXXXXXXXX',
  client_id: 'CLIENT_ID,
  client_secret: 'CLIENT',
  grant_type:'authorization_code',
  redirect_uri: 'postmessage' // the line to add
};
于 2019-06-19T08:32:41.533 回答
2

您需要通过 console.developer.google.com 向 Google 定义您的回调 url

因此,您需要按照以下步骤定义回调 URL:

  1. 转到 console.developer.google.com
  2. 选择您的项目。
  3. 单击左侧菜单上的“凭据”。
  4. 在“OAuth 2.0 客户端 ID”列表中单击您的客户端。
  5. 将您的回调 url 添加到“授权重定向 URI”列表中。

并做了。

于 2017-11-14T14:51:28.433 回答