google sign-in auth2 customize scope without openi

2019-05-18 17:09发布

问题:

I want to customize the scope to allow only "email" and "profile", without "openid"
because I would like to making it asking only to access to email and basic profile info.

I tried to do it using the meta:

<meta name="google-signin-scope" content="email profile">

or the js:

gapi.auth2.init({
    client_id: 'xxxxxxxxx.apps.googleusercontent.com',
    scope: 'email profile'
});

But it does not work: in the generated URL there is always the "openid" scope...

How can I "reset" the scope, and allow only what I want?

回答1:

BasicProfile requires 'profile email openid' scopes.

You can disable basic profile and require just 'profile email' scopes:

<meta name="google-signin-fetch_basic_profile" content="false">
<meta name="google-signin-scope" content="profile email">

Note that GoogleUser.getBasicProfile() will return null in this case. You have to manually get 'profile' and 'email' data.

Fully working example (you have to replace YOUR_CLIENT_ID with your actual client_id):

<html>
<head>
   <meta name="google-signin-client_id" content="YOUR_CLIENT_ID">
   <meta name="google-signin-fetch_basic_profile" content="false">
   <meta name="google-signin-scope" content="profile email">
</head>
<body>
  <script>
    function requestEmailData() { 
      gapi.client.load('oauth2', 'v2', function() {
        gapi.client.oauth2.userinfo.get().execute(function(resp) {
          // Shows user email
          console.log(resp.email);
        })
      });
    }

    function requestProfileData() {
      gapi.client.load('plus', 'v1', function() {
        gapi.client.plus.people.get( {'userId' : 'me'} ).execute(function(resp) {
          // Shows profile information
          console.log(resp);
        })
      });
    }

    function onSuccess() {
      gapi.load('client', function() {
        // based on http://stackoverflow.com/a/15384981
        requestEmailData();
        requestProfileData();
      });
    }
  </script>

  <div class="g-signin2" data-onsuccess="onSuccess"></div>

  <script src="https://apis.google.com/js/platform.js?onload=onLoad" async defer></script>
</body>
</html>

Note that you'll have to enable Google+ API in developers console to request 'profile' data. To do that

  1. go to https://console.developers.google.com/
  2. select project
  3. go to APIs & auth > APIs
  4. find and enable Google+ API.