Yvonne Aburrow
Yvonne Aburrow

Reputation: 2728

Google People API empty referer (but referer is set in console)

I am trying to access the Google People API to provide authentication for my Google App Engine app.

I am getting an error message about empty referrer, but I have my HTTP referrer set in the cloud console

{
  "error": {
    "code": 403,
    "message": "Requests from referer \u003cempty\u003e are blocked.",
    "status": "PERMISSION_DENIED",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.Help",
        "links": [
          {
            "description": "Google developer console API key",
            "url": "https://console.developers.google.com/project/824515690907/apiui/credential"
          }
        ]
      }
    ]
  }
}

Here's my gapi.js file:

  var apiKey = '<redacted>';
  var discoveryDocs = ["https://people.googleapis.com/$discovery/rest?version=v1"];

  var clientId = 'my-client-id.apps.googleusercontent.com';

  var scopes = 'profile';
  var authorizeButton = document.getElementById('authorize-button');
  var signoutButton = document.getElementById('signout-button');
  var mainDiv = document.getElementById('main');
  var editNav = document.getElementById('edit');
      authorizeButton.addEventListener("click", function(){ 
        handleAuthClick();
      });
      signoutButton.addEventListener("click", function(){
          handleSignoutClick();
      });
  function handleClientLoad() {
    // Load the API client and auth2 library
    gapi.load('client:auth2', initClient);
  }

function start() {

  gapi.client.init({
    'apiKey': apiKey,
    // clientId and scope are optional if auth is not required.
    'clientId': clientId,
    'scope': 'profile',
  }).then(function() {

    return gapi.client.request({
      'path': 'https://people.googleapis.com/v1/people/me?requestMask.includeField=person.names,person.emailAddresses',
      'headers': {'Content-Type': 'application/json','Referer': 'https://<my-app>.appspot.com/*'}
    })
  }).then(function(response) {
    console.log(response.result);
      updateSigninStatus(response);
  }, function(reason) {
    console.log('Error: ' + reason.result.error.message);
    authorizeButton.style.display = 'inline-block';
  });
};

gapi.load('client', start);
mainDiv.style.display = 'none';

/*functions*/
  function updateSigninStatus(response) {
    var name = response.result.names[0].givenName;
    var email = response.result.emailAddresses[0].value;
    authorizeButton.insertAdjacentHTML('beforebegin', '<span id="loggedinuser" rel="' + email + '">Logged in as ' + name + '</span>');
    authorizeButton.style.display = 'inline-block';
    }
}

  function handleAuthClick(event) {
    gapi.auth2.getAuthInstance().signIn();
    location.reload();
  }
  function handleSignoutClick(event) {
    gapi.auth2.getAuthInstance().signOut();
    var loggedin = document.getElementById("loggedinuser");
    loggedin.parentNode.removeChild(loggedin);
    var userStatus = document.getElementById("user_status");
    userStatus.parentNode.removeChild(userStatus);
    location.reload();
  }

I read another question & answer about putting in the referer as a parameter in the request, but I can't figure out where to put it.

Can anyone see what is wrong with my code? I had an earlier version working for a bit and then it went wrong.

Does anyone know of an up-to-date example of the Google API request script (the ones on GitHub provided by Google do not work).

Update

Just checked the headers in the network tab

Request URL:https://content-people.googleapis.com/v1/people/me?requestMask.includeField=person.names,person.emailAddresses&alt=json&key=<myApiKey>
Request Method:GET
Status Code:401 
Remote Address:216.58.204.74:443
Referrer Policy:no-referrer-when-downgrade

as per this answer on superuser about referrers and this answer on SO about a 403 error on a Google Maps API request.

Upvotes: 3

Views: 3019

Answers (1)

Yvonne Aburrow
Yvonne Aburrow

Reputation: 2728

gapi.js

  var apiKey = '<redacted>';
  var discoveryDocs = ["https://people.googleapis.com/$discovery/rest?version=v1"];

  var clientId = '<redacted>.apps.googleusercontent.com';
 var scopes = 'profile';
  var authorizeButton = document.getElementById('authorize-button');
  var signoutButton = document.getElementById('signout-button');
    var mainDiv = document.getElementById('main');
    var editNav = document.getElementById('edit');
  function handleClientLoad() {
    // Load the API client and auth2 library
    gapi.load('client:auth2', initClient);
    mainDiv.style.display = 'none';
  }
  function initClient() {
    gapi.client.init({
        apiKey: apiKey,
        discoveryDocs: discoveryDocs,
        clientId: clientId,
        scope: scopes
    }).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;
    });
  }
  function updateSigninStatus(isSignedIn) {
    if (isSignedIn) {
      authorizeButton.style.display = 'none';
      signoutButton.style.display = 'block';
      makeApiCall();
    } else {
      authorizeButton.style.display = 'block';
      signoutButton.style.display = 'none';
    }
  }
  function handleAuthClick(event) {
    gapi.auth2.getAuthInstance().signIn();
  }
  function handleSignoutClick(event) {
    gapi.auth2.getAuthInstance().signOut();
  }
  // Load the API and make an API call.  Display the results on the screen.
  function makeApiCall() {
    gapi.client.people.people.get({
      'resourceName': 'people/me',
      'requestMask.includeField': 'person.names,person.emailAddresses'
    }).then(function(response) {
        var name = response.result.names[0].givenName;
        var email = response.result.emailAddresses[0].value;
        authorizeButton.insertAdjacentHTML('beforebegin', '<span id="loggedinuser" rel="' + email + '">Logged in as ' + name + '</span>');
        }
    });
  }

index.html

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

adapted from: https://github.com/google/google-api-javascript-client/blob/master/samples/authSample.html

Upvotes: 1

Related Questions