如何通过OAuth 2.0在一个弹出验证与谷歌

How to authenticate with Google via OAuth 2.0 in a popup?

本文关键字:一个 验证 谷歌 OAuth 何通过      更新时间:2023-09-26

不好意思,编辑太大了。我没有正确地陈述我的问题,所以我要重新开始。

我正在尝试在HTML5中编写客户端应用程序。我不希望它被托管在一个网站上。我甚至不确定这是否可能,我对这种类型的应用程序相当陌生。

无论如何,我想访问谷歌服务,这需要验证,如OAuth。因为它是javascript,听起来像OAuth2是我需要的。

我试图打开谷歌身份验证在一个弹出(我有这部分),让用户允许访问,然后通过流回我的应用程序,然后可以查询谷歌服务。问题是1。当我使用response_type=code时,它要求用户复制/粘贴令牌到应用程序中,但如果我使用response_type=token,它要求我重定向到一个有效的URL,因为这不是托管在web服务器上,所以没有。

那么我如何使用OAuth,并让用户无缝地授予访问权限呢?

您应该为Google定义一些重定向URL,以便在身份验证完成后重定向到。如果你不能把你的网页放在任何网站上,你可以把它放在本地主机上。

关于从弹出到主父窗口的访问令牌,您可以在父窗口中设置一个计时器,该计时器不断检查弹出窗口的文档位置。一旦文档位置与重定向URL匹配,你就可以解析访问令牌,它将在URL本身中。

为了避免潜在的点击劫持,Google身份验证强制您进入完整的页面登录。我觉得你控制不了。

编辑注释后,这里是从Google OAuth2页面中提取的代码:

<body>
    <a href="javascript:poptastic('https://accounts.google.com/o/oauth2/auth?scope=https://www.google.com/m8/feeds&client_id=21302922996.apps.googleusercontent.com&redirect_uri=https://www.example.com/back&response_type=token');">Try
    out that example URL now</a>
<script>
    function poptastic(url) {
      var newWindow = window.open(url, 'name', 'height=600,width=450');
      if (window.focus) {
        newWindow.focus();
      }
    }
</script>
</body>

我相信你可以在Javascript中使用google api (gapi) for Oauth。使用Google api Client Library for JavaScript进行身份验证

您不需要用户复制/粘贴任何代码,也不需要提供重定向uri

所有你需要做的是:进入你的项目在谷歌开发控制台和生成以下内容:1. 生成新的客户端Id并选择选项"Installed Application"answers"Other"。2. 生成公共API密钥

以上文档中的示例代码:

// Set the required information
var clientId = 'YOUR CLIENT ID';
var apiKey = 'YOUR API KEY';
var scopes = 'https://www.googleapis.com/auth/plus.me';
// call the checkAuth method to begin authorization
function handleClientLoad() {
  gapi.client.setApiKey(apiKey); // api key goes here
  window.setTimeout(checkAuth,1);
}
// checkAuth calls the gapi authorize method with required parameters
function checkAuth() {
  gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult); // scope and client id go here
}
// check that there is no error and makeApi call
function handleAuthResult(authResult) {
  var authorizeButton = document.getElementById('authorize-button');
  if (authResult && !authResult.error) {
    makeApiCall();
  }
}
// API call can be made like this:
function makeApiCall() {
  gapi.client.load('plus', 'v1', function() {
    var request = gapi.client.plus.people.get({
      'userId': 'me'
    });
    request.execute(function(resp) {
      var heading = document.createElement('h4');
      var image = document.createElement('img');
      image.src = resp.image.url;
      heading.appendChild(image);
      heading.appendChild(document.createTextNode(resp.displayName));
      document.getElementById('content').appendChild(heading);
    });
  });
}

我已经为这个任务写了一个迷你JS库,看看它是否适合你。

https://github.com/timdream/wordcloud/blob/6d483cd91378e35b54e54efbc6f46ad2dd634113/go2.js

我最近正在开发另一个依赖于相同脚本的项目,所以我将这个项目隔离到一个独立的库项目中…检查下面的进度(如果有的话)