Google Apps SSO - First and Last Name with OAuth 2 without using Google+

ぃ、小莉子 提交于 2019-12-13 02:25:54

问题


I'm trying to implement Google Apps SSO using OAuth 2. I'm using the Google PHP Client Library for this purpose. I set the scope to 'email' and 'profile' during the authentication:

$this->client->setScopes('email', 'profile');

I'm able to get the email address with verifyIdToken, and the first name and the last name using Google Plus.

if ($this->client->getAccessToken()) {
    $tokenData = $this->client->verifyIdToken()->getAttributes();
    // Email: $tokenData['payload']['email']

    $plus = new \Google_Service_Plus($this->client);
    $me = $plus->people->get('me');
    // First name: $me['modelData']['name']['givenName']
    // Last name: $me['modelData']['name']['familyName']
}

The problem I'm facing is that many users use Google Apps without having a profile on Google+. My question is: How do I get the first and last name of the authenticated user without using Google Plus Service?

Note: I've tried posting to https://www.googleapis.com/oauth2/v1/userinfo with the correct access token, but this is soon to be deprecated and moreover, it also returns empty first name and last name for users who do not have Google+ profiles.


回答1:


I ended up using the OAuth 2.0 Service included in the library.

require_once 'Google/Service/Oauth2.php';

$oAuth2 = new \Google_Service_Oauth2($this->client);
$oAttr = $oAuth2->userinfo->get();

First Name is $oAttr['givenName'] and Last Name is $oAttr['familyName']

I also had to change the scope to "openid email profile":

$this->client->setScopes('openid email profile');


来源:https://stackoverflow.com/questions/25376457/google-apps-sso-first-and-last-name-with-oauth-2-without-using-google

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!