使用Google Apps脚本获取Gmail地址,错误:redirect_uri_mismatch

时间:2019-06-28 07:58:54

标签: javascript html google-apps-script google-signin google-contacts-api

我尝试使用我的应用脚本获取用户的Gmail地址。我已经咨询了几个地方:

https://developers.google.com/identity/sign-in/web/sign-in

https://developers.google.com/apps-script/guides/html/

在我之前发布的问题中,但我做不到,并且有一个新问题。

此代码文件gs:

function doGet(e) {

 var tmp = HtmlService.createTemplateFromFile("testapi");
 return tmp.evaluate(); 

}

此代码文件html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="google-signin-client_id" content="1xxxxxxxxxx-xxxxxxxxi87eht.apps.googleusercontent.com">
    <title>Oauth2 web</title>

    <!-- Google library -->
    <script src="https://apis.google.com/js/platform.js" async defer></script>

    <!-- Jquery library to print the information easier -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

    <!-- Bootstrap library for the button style-->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div id="profileinfo">
</div>
<div class="g-signin2" data-onsuccess="onSignIn"></div>

<script>
            function onSignIn(googleUser) {
              var profile = googleUser.getBasicProfile();
              console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
              console.log('Name: ' + profile.getName());
              console.log('Image URL: ' + profile.getImageUrl());
              console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.

              $("#profileinfo").append("<h2>Sup " + profile.getName() + ", welcome home my friend</h2>");
              $("#profileinfo").append("<img style='width:250px;height:250px' src='" + profile.getImageUrl() + "'><br><br>");
              $("#profileinfo").append("<p>Your email is: " + profile.getEmail() + "</p>");

            }
        </script>

<button type="button" class="btn btn-danger" onclick="signOut();">Sign out</button>

<script>
            function signOut() {
               var auth2 = gapi.auth2.getAuthInstance();
               auth2.signOut().then(function () {
                 console.log('User signed out.');
               $("#profileinfo").empty();
               $("#profileinfo").append("<h2>Goodbye old friend</h2>");
               });
            }
        </script>
</body>
</html>

create clientID console.developers.google.com

URL of Apps script

error

3 个答案:

答案 0 :(得分:1)

我转载了您的步骤,并且确实检索了html,但是当您尝试登录时,会在弹出窗口中引发以下错误:

“Error: redirect_uri_mismatch

The JavaScript origin in the request, https://XXXXXXX-script.googleusercontent.com, does not match the ones authorized for the OAuth client.”

您需要从错误消息中复制URL,然后执行以下步骤:

1)在Google云中选择项目,然后转到凭据-> Oauth同意屏幕,在授权域中添加“ googleusercontent.com”。

2)编辑您的凭据并将您之前获得的URL添加到“ Authorized JavaScript origins”部分。

3)部署为新版本的Web应用。

如果我没看错,那应该行得通,尽管有几点要指出如何部署Web应用程序:

1)如果您设置了部署选项,以在用户访问应用程序时执行该应用程序,则当您通过链接访问时,应用程序脚本将提示其自己的同意屏幕进行登录,然后单击登录。选项,它将自动以已经登录的用户登录。

2)如果您设置了部署选项以按需执行应用程序,并且在访问选项中选择了“任何人,甚至匿名”,当您单击登录选项时,它将提示您预期的oauth同意屏幕进行登录。唯一的是,当您注销并再次单击“登录”按钮时,它将自动使用以前的凭据登录(在普通服务器中,它将再次提示您同意屏幕)。

无需实施Oauth,可以将部署选项设置为“ 1)”中的设置,然后使用App Script中的User对象获取用户的电子邮件,尽管那是您唯一可以从那里获得的信息。 [1]。

[1] https://developers.google.com/apps-script/reference/base/user

答案 1 :(得分:1)

如果我很了解您想在前端获得电子邮件和用户个人资料信息,则不需要做所有这些复杂的事情。

在后端创建此功能:

function getUser(){
  //Session.getEffectiveUser().getEmail(); // Just for scope
  var url = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json";
  var param = {
    method      : "Get",
    headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
    'muteHttpExceptions' :true
  };
  var html = UrlFetchApp.fetch(url,param);
  var data = JSON.parse(html.getContentText());
  Logger.log(JSON.stringify(data))
  /* Result is JSON
  {"id":"Google User ID","email":"user@mail.com","verified_email":true,"picture":"https://xxxxxxxxxxxxxxxxx/photo.jpg"}
  */
  return data
}

然后在前端,您可以调用此函数以获取用户详细信息:

function getUserDetails(){
  google.script.run
        .withSuccessHandler(function(user) {
            //Do some stuffs with user details
            // Email is in user.email
          })
        .withFailureHandler(function(msg) {
            console.log(msg);
          })
        .getUser(); 
}

在脚本请求Session.getEffectiveUser()。getEmail()时,用户授予范围允许获取用户信息。

然后,您只需查询https://www.googleapis.com/oauth2/v1/userinfo?alt=json端点即可获取用户详细信息。

史蒂芬(Stéphane)

答案 2 :(得分:-1)

在Google Apps脚本中创建的Web应用程序始终在IFRAME中提供,并且无法在IFRAME外部访问。

因此,标准的Google登录组件无法嵌入到这些应用中。