Google 使用 Javascript API 登录而不触发弹出窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27905780/
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-10-28 08:09:10  来源:igfitidea点击:

Google sign-in using Javascript API without triggering popup

javascriptjquerygoogle-apigoogle-plusgoogle-oauth

提问by terriblecoder45

I am using following code for users to be able to login using their Google account via Javascript API.

我正在使用以下代码让用户能够通过 Javascript API 使用他们的 Google 帐户登录。

HTML

HTML

<a id="gp_login" href="javascript:void(0)" onclick="javascript:googleAuth()">Login using Google</a>

<a id="gp_login" href="javascript:void(0)" onclick="javascript:googleAuth()">Login using Google</a>

Javascript

Javascript

function gPOnLoad(){
     // G+ api loaded
     document.getElementById('gp_login').style.display = 'block';
}
function googleAuth() {
    gapi.auth.signIn({
        callback: gPSignInCallback,
        clientid: googleKey,
        cookiepolicy: "single_host_origin",
        requestvisibleactions: "http://schema.org/AddAction",
        scope: "https://www.googleapis.com/auth/plus.login email"
    })
}

function gPSignInCallback(e) {
    if (e["status"]["signed_in"]) {
        gapi.client.load("plus", "v1", function() {
            if (e["access_token"]) {
                getProfile()
            } else if (e["error"]) {
                console.log("There was an error: " + e["error"])
            }
        })
    } else {
        console.log("Sign-in state: " + e["error"])
    }
}

function getProfile() {
    var e = gapi.client.plus.people.get({
        userId: "me"
    });
    e.execute(function(e) {
        if (e.error) {
            console.log(e.message);
            return
        } else if (e.id) {
            // save profile data
        }
    })
}(function() {
    var e = document.createElement("script");
    e.type = "text/javascript";
    e.async = true;
    e.src = "https://apis.google.com/js/client:platform.js?onload=gPOnLoad";
    var t = document.getElementsByTagName("script")[0];
    t.parentNode.insertBefore(e, t)
})()

This code is working fine. I want to use the above code (using Javascript) to login user from their Google account without triggering a popup window. Like, user clicks the login link, asked for app permissions in the same window/tab, user grants permission, user redirected back to the page where Google login link was, profile data is saved and user is logged in.

这段代码工作正常。我想使用上面的代码(使用 Javascript)从他们的 Google 帐户登录用户而不触发弹出窗口。例如,用户单击登录链接,在同一窗口/选项卡中请求应用程序权限,用户授予权限,用户重定向回 Google 登录链接所在的页面,个人资料数据被保存并且用户已登录。

采纳答案by Jaros?aw Gomu?ka

Such functionality is not provided through Google API. You should stick with gapi.auth.signIn. I know just one way to make it work, but it's very hacky.

此类功能不是通过 Google API 提供的。你应该坚持使用gapi.auth.signIn。我只知道一种使它工作的方法,但它非常笨拙。

gapi.auth.signIn opens authentication window. Save authentication window url in your app1. Instead of calling gapi.auth.signIn, redirect user to that url.

gapi.auth.signIn 打开身份验证窗口。在您的应用1 中保存身份验证窗口 url 。不是调用 gapi.auth.signIn,而是将用户重定向到该 url。

To redirect successful authentication back to your website, add/modify redirect_url param in the url2. Keep in mind that redirect_uri must be registered in developers console.

要将成功的身份验证重定向回您的网站,请在 url 2 中添加/修改 redirect_url 参数。请记住,redirect_uri 必须在开发者控制台中注册。

Example: https://accounts.google.com/o/oauth2/auth?client_id=1234567890.apps.googleusercontent.com&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fplus.login&immediate=false&response_type=token&redirect_uri=http://example.com

示例:https: //accounts.google.com/o/oauth2/auth?client_id=1234567890.apps.googleusercontent.com &scope =https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fplus.login &immediate =false &response_type =token &redirect_uri = http://example.com

This way google will redirect user back to your website. access_token is provided through GET params.

这样谷歌会将用户重定向回您的网站。access_token 是通过 GET 参数提供的。

1If google changes their API this may break (since this method bypasses JS API and assumes that all those params in the url will be supported for ever).

1如果 google 更改他们的 API,这可能会中断(因为此方法绕过 JS API 并假设 url 中的所有这些参数都将被永远支持)。

2Redirect_url is introduced in offline access flow documentation. I don't think this param was intended to work in any other cases.

2离线访问流程文档中引入了 Redirect_url 。我不认为这个参数是为了在任何其他情况下工作。

I strongly advise not to use this idea (since it bypasses JS API and uses undocumented functionality). Stick with gapi.auth.signIn.

我强烈建议不要使用这个想法(因为它绕过了 JS API 并使用了未记录的功能)。坚持使用gapi.auth.signIn。

回答by mrelva

You can the use ux_modeparameter (options are 'redirect'or 'popup') and set a redirect_uriif you want to redirect to a different page.

如果您想重定向到不同的页面,您可以使用ux_mode参数(选项为'redirect''popup')并设置redirect_uri

It's also necessary to authorize the URL for the OAuth client on your google project page.

还需要在您的 google 项目页面上为 OAuth 客户端的 URL 授权。

  function initClient() {
    gapi.client.init({
      apiKey: API_KEY,
      clientId: CLIENT_ID,
      discoveryDocs: DISCOVERY_DOCS,
      scope: SCOPES,
      ux_mode: 'redirect',
      //redirect_uri: custom url to redirect'
    }).then(function () {
      // Listen for sign-in state changes.
      gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

      // Handle the initial sign-in state.
      updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      authorizeButton.onclick = handleAuthClick;
      signoutButton.onclick = handleSignoutClick;
    });
  }