在gapi.auth2.authorize呼叫

时间:2018-12-26 21:45:06

标签: google-oauth authorize

我们允许用户选择通过oauth使用其Google凭据向我们的应用程序进行身份验证。一切正常,但是google正在终止我们用来获取其电子邮件地址的google + api调用,这对我们来说是一个问题。不幸的是,我为找到用于检索电子邮件的正确方法而大吃一惊,因此任何建议都会受到赞赏。

这是当前代码:                               var developerKey ='我们的钥匙';             var clientId ='我们的ID';             var scope = ['email'];             var oauthToken;

        // authorize the current user with Google
        function authorizeGoogleUser() {
            gapi.auth2.authorize({
                'client_id': clientId,
                'scope': scope,
                'immediate': false
            },
            handleAuthorizeCallback);
        }

        // handle callback from the authorization, doing the user lookup if valid
        function handleAuthorizeCallback(authResult) {
            if (authResult && !authResult.error) {
                //save the token and do the user lookup
                oauthToken = authResult.access_token;
                getGoogleUserDetails();
            }
        }

        // lookup user details, prompting for authentication/permission if needed
        function getGoogleUserDetails() {
            if (oauthToken == null) {
                //authenticate
                gapi.load('auth2', { 'callback': authorizeGoogleUser });
            }
            else {
                //already athenticated, so continue to do user lookup
                gapi.client.load('plus', 'v1', apiClientLoaded);
               }
        }

        function apiClientLoaded() {
//
// THIS IS THE PORTION THAT NEEDS REDESIGNED AS THIS CALL IS GOING AWAY
//

            gapi.client.plus.people.get({ userId: 'me' }).execute(handleGetUserResponse);
        }

        //do user lookup
        function handleGetUserResponse(resp) {
            if (resp && resp.emails.length > 0) {
                //get primary email address
                var primaryEmail;
                for (var i = 0; i < resp.emails.length; i++) {
                    if (resp.emails[i].type === 'account') primaryEmail = resp.emails[i].value;
                }

                //call server-side method to encrypt email and refresh page
                $.ajax({
                    type: "POST",
                    url: "OUR URL",
                    data: "{'emailAddress': '" + primaryEmail + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (retVal) {
                        if (retVal.d !== '') {
                            window.location.href = retVal.d;
                        }
                    }
                });
            }
        }

1 个答案:

答案 0 :(得分:0)

我重写了整个过程,它现在适用于除IE之外的所有浏览器。任何有关IE的建议都会被接受。不幸的是,IE并没有真正抛出错误,而是进行了身份验证,但从未返回到侦听器。

<script type="text/javascript" src="https://apis.google.com/js/api.js" "></script>
<script type="text/javascript">
  var apiKey = 'our key;
  var discoveryDocs = ["https://people.googleapis.com/$discovery/rest?version=v1"];
  var clientId = 'our client id;
  var scopes = 'profile';

  function handleClientLoad() {
    // Load the API client and auth2 library
      gapi.load('client:auth2', initClient);
   }

    function initClient() {
    gapi.client.init({
        apiKey: apiKey,
        discoveryDocs: discoveryDocs,
        clientId: clientId,
        scope: scopes,
        'immediate': false
    }).then(function () {
      // Listen for sign-in state changes.
      gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
    });
  }

  function updateSigninStatus(isSignedIn) {
    if (isSignedIn) {
                makeApiCall();
    }
  }

  function handleAuthClick() {
    // here is my current issue, need to see if the user is signed in or not
    var isSignedIn = gapi.auth2.getAuthInstance().isSignedIn.get();
    if (isSignedIn) {
        makeApiCall();
    }
    else {
    gapi.auth2.getAuthInstance().signIn();
    }
  }

  function makeApiCall() {
    // Load the API and make an API call.  Display the results on the screen.
    gapi.client.people.people.get({ 
      'resourceName': 'people/me',
      'requestMask.includeField': 'person.emailAddresses'
    }).then(function(resp) {
      var email = resp.result.emailAddresses[0].value;
      //call server-side method to encrypt email and refresh page
      $.ajax({
        type: "POST",
        url: "our url",
        data: "{'emailAddress': '" + email + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (retVal) {
            if (retVal.d !== '') {
                window.location.href = retVal.d;
            }
        }   
      });
    });
  }
</script>

<script type="text/javascript" async defer src="https://apis.google.com/js/api.js" 
  onload="this.onload=function(){};handleClientLoad()" 
  onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

<asp:linkButton ID = "btnGoogle" runat="server" CssClass="LinkBtn BtnContainerVertical" Width="200px" CausesValidation="false" OnClientClick="handleAuthClick(); return false;" ><img src="../Images/google.png" class="LinkBtnIcon" style="height:20px" />Google Login</asp:linkButton>