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

后端 未结 4 1538
梦谈多话
梦谈多话 2020-12-04 09:51

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

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 10:23

    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

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

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

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

提交回复
热议问题