How to use Google Single Sign-On without the PHP SDK

Originally published 2014-07-30 17:45:35 by Nathan England
related tags: google php sdk, programming, single sign-on,


Google Single Sign-On with OAuth2 Made Easy

In a previous article I explained a little bit and showed some examples how easy it is to connect to Facebook to retrieve user information and verified data for account creation on your own website. Similarly, I want to demonstrate how easy it is to access public profile information using Google. You need to create a Project with Google in the Developers Console https://console.developers.google.com/project. Within the project setup you need to enable at least the Google+ API. Next you need to configure your credentials and create a Client ID for web application. Be sure to note the correct REDIRECT URIs or this won't work. And on to the code...

I make a few assumptions here. There are dozens of websites that explain with a nice graphic how OAuth2 works and that you need to request a code, return the code for an access token and so on... I'm going to skip all of that. I'm going to assume you have half a clue to what you are doing and just present the code with a little commentary. I hope this helps you...

Create a basic configuration template that you can include when necessary that will contain your CLIENT ID, CLIENT_SECRET, and REDIRECT_URIs.

<?php // filename google.config.php
define('GOOGLE_CLIENT_ID', '9234798-dfadfdfadsSFDSSfwfadfa.apps.googleusercontent.com');
define('GOOGLE_CLIENT_SECRET', '-ZXy32fJCxi-865dsfaQEWdsyhL__vpg');
define('GOOGLE_REDIRECT_URI', HTTP_HOST . '/user/google/authorize');
define('HTTP_HOST', 'http://www.mydomain.com');
define('STATE', md5(uniqid(rand(), TRUE)));

Google Login URL

Present the user with a button to click on that will begin the Google+ authorization process. I highly suggest you create a class to handle this for you, but in the end, a function will do just fine. So create a function to create the Login URL.

function getLoginUrl() {
               $loginUrl = "https://accounts.google.com/o/oauth2/auth?"
                    . "client_id=" . GOOGLE_CLIENT_ID
                    . "&redirect_uri=" . GOOGLE_REDIRECT_URI
                    . "&state=" . STATE
                    . "&response_type=code"
                    . "&scope=https://www.googleapis.com/auth/plus.login profile email" // openid%20profile
                    . "&include_granted_scopes=true";

               return $loginUrl;
          }

Any time you need to create a login button you can issue the code like so:

<a href="<?php echo getLoginUrl; ?>">Google Login</a>

Though I would highly recommend you dress that up a little bit! Once the user clicks that link it will submit your information to Google and as long as your ID and REDIRECT match what they have in their systems it will redirect the user to your GOOGLE_REDIRECT_URI and provide you with your state and a special code. You really need to verify the state field is the same as the one you sent. This is a basic metric to secure against cross-site scripting. Once you confirm the state matches you can capture the code property:

$google_code = $_GET['code'];

Using that code we can request the Access Token.

Requesting the Access Token

Now that we have that code we are going to create another function that will request the access token. Google, unlike Facebook, requires a POST to their systems with your information, so we are going to create a curl function like we did with Facebook, but also a curl_post function specific for Google. Create the following Functions:

function curl_post($url, $post) {
               $curl = curl_init($url);
               curl_setopt($curl, CURLOPT_POST, TRUE);
               curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
               curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
               curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
               curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
               $json_response = curl_exec($curl);
               curl_close($curl);
               return $json_response;
          }

function curl($url) {
               $curl = curl_init();
               curl_setopt($curl, CURLOPT_URL, $url);
               curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
               $json_response = curl_exec($curl);
               curl_close($curl);
               return $json_response;
          }

function getAccessToken($google_code) {
               $token_url = "https://accounts.google.com/o/oauth2/token";
               $post = array(
                    "code" => $google_code,
                    "client_id" => GOOGLE_CLIENT_ID,
                    "client_secret" => GOOGLE_CLIENT_SECRET,
                    "redirect_uri" => GOOGLE_REDIRECT_URI,
                    "grant_type" => "authorization_code"
               );
               $response = curl_post($token_url, $post);

               if ($response) {
                    $authObj = json_decode($response);
                    print_array($authObj);
               }
               if (isset($authObj->refresh_token)) {
                    $this->Google_RefreshToken = $authObj->refresh_token;
               }
               if (isset($authObj->access_token)) {
                    return $authObj;
               }else {
                    return FALSE;
               }
          }

Use the code you recieve to call this function like so:

$authObj = getAccessToken($google_code);
$access_token = $authObj->access_token;

The $authObj returned will be a json decoded object containing your Refresh Token, if you want to use it, the necessary Access Token, and the Id Token. Finally, we can request the users information from Google's OAuth2 userinfo api. Create the final function:

function getUserInfo($access_token) {
               $user_info_url = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" . $access_token;
               if ($user = json_decode(curl($user_info_url))) {
                    return $user;
               };
               return FALSE;
          }

$user = getuserInfo($access_token);

Now you have some public profile information necessary to populate your own database with and create the user account for your new user. Take a look at the data you have:

print_r($user);

You should create your own user_id in your system and match it up with Googles ID for this user. But now you have a First Name (Given Name), Last Name (Family Name), a Nickname (name), and a little bit more.

I much prefer capturing my users information like this. I'm not interested in who their friends are, posting anything for them, or gathering information on them. I just want to know the email they give me is verified so I can create a trusted account for them. This easy method allows me to do just that. Afterwards, if I want to provide the means for a user to share something with their friends I will include the Javascript SDK and let Google do the work for me.

I hope you enjoyed this tutorial. Hit me up on Google+ or use my contact form if you would like to send me comments or ask questions!