Javascript 使用Google Apps脚本获取gmail地址,错误:重定向\u uri\u不匹配

Javascript 使用Google Apps脚本获取gmail地址,错误:重定向\u uri\u不匹配,javascript,html,google-apps-script,google-signin,Javascript,Html,Google Apps Script,Google Signin,我尝试使用我的应用程序脚本获取用户的gmail地址。我咨询了几个地方: 在我之前发布的问题中,但我做不到,出现了一个新问题 此代码文件包括: function doGet(e) { var tmp = HtmlService.createTemplateFromFile("testapi"); return tmp.evaluate(); } 此代码文件为html: <!DOCTYPE html> <html> <head

我尝试使用我的应用程序脚本获取用户的gmail地址。我咨询了几个地方:

在我之前发布的问题中,但我做不到,出现了一个新问题

此代码文件包括:

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>

在Google Apps脚本中创建的Web应用程序始终在IFRAME中提供,不能在IFRAME之外访问


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

我复制了您的步骤,它确实检索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 cloud中选择项目,进入凭证->Oauth同意屏幕,在授权域中添加“googleusercontent.com”

2编辑您的凭证,并将您之前获得的URL添加到“授权JavaScript来源”部分

3在新版本中作为web应用程序部署

如果我理解正确的话,这应该行得通,不过在部署web应用程序时需要指出以下几点:

1如果您将部署选项设置为以用户访问应用程序的身份执行应用程序,则当您使用链接进行访问时,应用程序脚本将提示其自己的同意屏幕进行登录,然后当您单击登录选项时,它将自动与已登录的用户进行登录

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

无需实现Oauth,您可以将部署选项设置为“1”中的设置,然后使用应用程序脚本中的用户对象来获取用户的电子邮件,尽管这是您可以从那里获得的唯一信息[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时,将向用户授予作用域以允许获取用户信息

然后,您只需查询端点即可获得用户详细信息


斯泰芬尼

引用了准确的错误。好的,我已经编辑过了,不是真的。我试过一次,成功了。我认为origins/redirect也应该设置为script.googleusercontent.com。但它能工作。@theMaster我试着设置为script.googleusercontent.com,但它也不能run@TheMaster是 啊非常感谢你!感谢您的热情,我已经成功地运行了它^^^您提供的/oauth2/v1/userinfo端点上的任何源代码/文档?它是Google oauth2文档的一部分,但找不到它。我用它已经很久了,所以我复制粘贴代码。谢谢你的帮助,但它只得到我的gmail地址。我希望所有用户在访问应用程序链接时都能使用我的应用程序。不可能从应用程序中执行此操作。唯一的解决办法是将这些信息存储在某个地方。可以是外部数据库、脚本属性等。我仍然没有遵循这些,仍然报告相同的错误:重定向\u uri\u请求中的JavaScript源不匹配,与OAuth客户端授权的不匹配。->我不知道链接请求是从何处创建的?这个链接我也不知道URL是从何处创建的,但您必须将它完全从https://添加到授权的javascript源输入中,直到最后。非常感谢!我已经成功地运行了它^^