如何通过OAuth 2.0在Google浏览器中进行身份validation?

对不起,一个大的编辑。 我开始了,因为我没有正确地陈述我的问题。

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

无论如何,我想访问Google服务,这需要validation,如OAuth。 因为它是JavaScript,听起来像OAuth2是我所需要的。

我试图打开谷歌身份validationpopup式(我有这部分),让用户允许访问,然后将stream量传回我的应用程序,然后可以查询谷歌服务。 问题是1.它要求用户复制/粘贴一个令牌到应用程序,每当我使用response_type=code ,但如果我使用response_type=token它需要我redirect回有效的URL,因为这不是托pipe一个networking服务器,没有。

那么我怎样才能使用OAuth,并让用户无缝授权?

您应该在Google身份validation完成后为Google定义一些redirecturl。 如果你不能在任何网站上托pipe你的页面,你可以很好地托pipe在本地主机。

关于从popup窗口获取访问令牌到主父窗口,您可以在父窗口中设置一个定时器,该窗口继续检查popup窗口的文档位置。 一旦文件位置与redirectURL匹配,你就可以parsing访问令牌,这个令牌将会在URL本身中。

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

希望你会发现它有用。

为了避免可能的点击问题 ,Google身份validation会强制您进行整页login。 我不认为你可以控制。

编辑后评论,这里是一个代码从谷歌的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。 以下是文档: 使用JavaScript的Google API客户端库进行身份validation

你不会要求用户复制/粘贴任何代码,你不会要求提供一个redirect的URI

您只需要:在Google Developers Console中转到您的项目并生成以下内容:1.生成新的客户端ID并select“已安装的应用程序”和“其他”选项。 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/master/go2.js

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