Javascript 如何在弹出窗口中通过 OAuth 2.0 向 Google 进行身份验证?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7947038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:10:14  来源:igfitidea点击:

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

javascriptoauth

提问by esac

Sorry for a big edit. I am starting over as I am not stating my question correctly.

抱歉进行了大编辑。我重新开始,因为我没有正确说明我的问题。

I am trying to write a client side app in HTML5. I do not want it to be hosted on a website. I am not even sure this is possible, I am fairly new to this type of application.

我正在尝试用 HTML5 编写客户端应用程序。我不希望它托管在网站上。我什至不确定这是可能的,我对这种类型的应用程序还很陌生。

Anyway, I want to access Google services, which requires authenticate such as OAuth. Being that it is javascript, it sounds like OAuth2 is what I need.

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

I am trying to open up the google authentication in a popup (I have this part), let the user allow access, and then pass flow back to my application which can then query Google services. Problem is either 1. it asks the user to copy/paste a token into the app whenever I use response_type=code, but if I use response_type=tokenit requires that I redirect back to a valid URL which, since this is not hosted on a webserver, there is none.

我正在尝试在弹出窗口中打开 google 身份验证(我有这部分),让用户允许访问,然后将流程传回我的应用程序,然后可以查询 Google 服务。问题是 1. 每当我使用它时,它都会要求用户将令牌复制/粘贴到应用程序中response_type=code,但是如果我使用response_type=token它,则需要我重定向回一个有效的 URL,因为它没有托管在网络服务器上,因此没有.

So how can I use OAuth, and let the user grant access seamlessly?

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

回答by saiy2k

You should have some Redirect URL defined for Google to redirect to after the authentication is done. If you cant host your pages on any web site, you can very well host it in local host.

您应该为 Google 定义一些重定向 URL,以便在身份验证完成后重定向到该 URL。如果您无法在任何网站上托管您的页面,您可以很好地将其托管在本地主机上。

Regarding getting the access token from the popup to the main parent window, you can setup a timer in parent window which keeps on checking the document location of the popup. Once the document location matches the Redirect URL, u can parse the access token which will will be in the URL itself.

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

I wrote a tutorial on exactly the same problem (using local host) yesterday and here is the link: http://www.gethugames.in/2012/04/authentication-and-authorization-for-google-apis-in-javascript-popup-window-tutorial.html

我昨天写了一个关于完全相同问题(使用本地主机)的教程,这里是链接:http: //www.gethugames.in/2012/04/authentication-and-authorization-for-google-apis-in-javascript -popup-window-tutorial.html

Hope you will find it useful.

希望你会发现它很有用。

回答by Mic

To avoid a potential click Hymaning, Google authentication forces you to go to a full page login. I don't think you can control that.

为避免潜在的点击劫持,Google 身份验证会强制您进入完整页面登录。我认为你无法控制。

EDITafter comment, here is a code extracted from the Google OAuth2 pagethat does it:

评论后编辑,这是从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>

回答by mlfan

I believe you can use google api (gapi) for Oauth in Javascript. Here is the documentation: Authentication using the Google APIs Client Library for JavaScript

我相信您可以在 Javascript 中将 google api (gapi) 用于 Oauth。这是文档:使用 Google API 客户端库进行 JavaScript 身份验证

You will not require the user to copy/paste any codes and you will not require to provide a redirect uri

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

All you need to do is: Go to your project in Google Developers Consoleand generate the following: 1. Generate new Client Id and choose options 'Installed Application' and 'Other'. 2. Generate a Public API Key

您需要做的就是:在Google Developers Console 中转到您的项目并生成以下内容: 1. 生成新的客户端 ID 并选择选项“已安装的应用程序”和“其他”。2. 生成公共 API 密钥

Sample Code from the above documentation:

上述文档中的示例代码:

// 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);
    });
  });
}

回答by timdream

I've written a mini JS library for the task, take it and see if it works for you.

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

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

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

I am recently developing another project that rely on the same script, so I am isolating this one into an independent library project... check the progress follows (if there are).

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