Authenticating with OAuth 2.0 for Google API Access with PHP

Google is leading developers to OAuth 2.0 for access to its API’s:

Given the security implications of getting the implementation correct, we strongly encourage developers to use OAuth 2.0 libraries when interacting with Google’s OAuth 2.0 endpoints (see Client libraries for more information). Over time, more features will be added to these libraries.

Steps

  1. Register the app with Google
  2. Create login URL and retrieve “code”
  3. Exchange “code” for access token
  4. Send access token with API requests (details in this post)

Google details the instructions in Using OAuth 2.0 to Access Google APIs.

Steps for registering your app can be found in APIs Client Library for PHP.

Google scope values for its API’s can be found in the OAuth 2.0 Playground.

Create Login URL and Retrieve “Code”

Parameters for Login URL

Client id and client secret are set by Google when the app is registered for api access in the Google APIs Console.

The redirect uri is a location on the server that the user is sent to after authenticating. This uri is registered in the Google APIs Console during app registration.

These values can be included as a separate file so the values can easily be swapped out on a per app basis.

$client_id = "1111111111111.apps.googleusercontent.com"; //your client id
$client_secret = "XxxXXxxXXxXXxXxXXXxXXXX"; //your client secret 
$redirect_uri = "http://YOUR-SITE.com/YOUR-PATH/";
$scope = "https://GOOGLE-SCOPE-TO-ACCESS"; //google scope to access
$state = "profile"; //optional
$access_type = "offline"; //optional - allows for retrieval of refresh_token for offline access

User Login URL

The login URL will prompt the user for permission to access their Google content via the app and a “code” request variable will be returned in the URL. See Forming the URL for more detailed information.

$loginUrl = sprintf("https://accounts.google.com/o/oauth2/auth?scope=%s&state=%s&redirect_uri=%s&response_type=code&client_id=%s&access_type=%s", $scope, $state, $redirect_uri, $client_id, $access_type);

<a href="<?php echo $loginUrl ?>">Login with Google account using OAuth 2.0</a>

Returned URL example (http://YOUR-SITE.com/YOUR-PATH/ is your redirect uri):


http://YOUR-SITE.com/YOUR-PATH/?state=profile&code=1/fFBGRNJru1FQd44AzqT3Zg

Exchange “Code” for Access Token

If access type was set to “offline” in the login URL, a refresh token will be sent with the access token so the data can be accessed without prompting the user again.

//Oauth 2.0: exchange token for session token so multiple calls can be made to api
if(isset($_REQUEST['code'])){
	$_SESSION['accessToken'] = get_oauth2_token($_REQUEST['code']);
}

//returns session token for calls to API using oauth 2.0
function get_oauth2_token($code) {
	global $client_id;
	global $client_secret;
	global $redirect_uri;
	
	$oauth2token_url = "https://accounts.google.com/o/oauth2/token";
	$clienttoken_post = array(
	"code" => $code,
	"client_id" => $client_id,
	"client_secret" => $client_secret,
	"redirect_uri" => $redirect_uri,
	"grant_type" => "authorization_code"
	);
	
	$curl = curl_init($oauth2token_url);

	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $clienttoken_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);

	$authObj = json_decode($json_response);
	
	if (isset($authObj->refresh_token)){
        //refresh token only granted on first authorization for offline access
        //save to db for future use (db saving not included in example)
		global $refreshToken;
		$refreshToken = $authObj->refresh_token;
	}
			  
	$accessToken = $authObj->access_token;
	return $accessToken;
}

You now have an access token to present to the Google API of your choice (specified in the scope) for data.

Demo

Download code

Posted in Uncategorized. Permalink. Both comments and trackbacks are closed.

2 Comments

  1. cris
    January 17, 2012 at 8:41 pm | Permalink

    nice tut,

    it looks like i get: Trying to get property of non-object for this line; $accessToken = $authObj->access_token;

    what do you thing?

    thanks

  2. Filip
    December 28, 2011 at 9:17 am | Permalink

    Thanks for your excellent tutorial and code. It helped me achieving the Google authentication I was looking for.