[Oauth]使用 OAuth 2.0 存取 Google APIs(for Login)

要使用Google API第一步要先申請註冊project(在左邊API Access中新增Client ID for web applications )
Google API

接著要透過OAuth認證來登入Google(Google Using OAuth 2.0 for Login)

首先測試Client ID是否能操作API
對https://accounts.google.com/o/oauth2/auth這個Google的Web Service以GET參數的方式傳入API存取權限
傳入的參數有:
response_type:可傳入token或code(之後Google會依照此參數回傳不同的內容型態)
client_id:該Project的Client ID
redirect_uri:該Project的Redirect URIs(Google會把token傳到該url)
scope:該Projec可存取的權限,可傳入https://www.googleapis.com/auth/userinfo.profile(使用者基本資料)和https://www.googleapis.com/auth/userinfo.email(使用者信箱資料),兩個可以用+號串起來
例如

https://accounts.google.com/o/oauth2/auth?response_type=token&
client_id=12345.apps.googleusercontent.com&
redirect_uri=http://blog.johnsonlu.org/oauth2callback&
scope=https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email

執行並登入後,Google會將token(code)以#(錨點)的方式帶到該Project的Redirect URIs上,這樣就算測試成功

另外
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={Your accessToken}
這個把token傳入到這個Web Service,它會幫你把token的資訊解析出來

不過,要拿來開發系統建議還是用Google所提供的apiClient(Google API PHP Client)

因為是使用OAuth2,所以src/config.php裡的OAuth2 Settings都要填上資料(Client ID等等)

PHP

<?php
	require_once 'src/apiClient.php';
	require_once 'src/contrib/apiOauth2Service.php';
	session_start();
	
	//建立apiClient
	$client = new apiClient();
	
	//建立Oauth2 Service
	$oauth2 = new apiOauth2Service($client);
	
	//處理回傳的code
	if (isset($_GET['code'])) {
	  $client->authenticate();
	  $_SESSION['token'] = $client->getAccessToken();
	  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
	  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
	}
	//設定Token
	if (isset($_SESSION['token'])) {
	 $client->setAccessToken($_SESSION['token']);
	}
	
	//取消Session
	if (isset($_REQUEST['logout'])) {
	  unset($_SESSION['token']);
	  $client->revokeToken();
	}
	
	if ($client->getAccessToken()) {
	  $user = $oauth2->userinfo->get();
	  //用filter過濾
	  $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
	  $img = filter_var($user['picture'], FILTER_VALIDATE_URL);
	  $personMarkup = "$email<div><img src='$img?sz=50'></div>";
	  //再取得一次Token
	  $_SESSION['token'] = $client->getAccessToken();
	} 
	else{
	  $authUrl = $client->createAuthUrl();
	}
	
?>

HTML

<html>
	<head>
		<meta charset="utf-8"/>
		<title>TEST</title>
	</head>
	<body>
		<?php if(isset($personMarkup)): ?>
		<?php print $personMarkup ?>
		<?php endif ?>
		<?php
		  if(isset($authUrl)) {
			print "<a class='login' href='$authUrl'>Connect Me!</a>";
		  } else {
		   print "<a class='logout' href='?logout'>Logout</a>";
		  }
		?>
	</body>
</html>

[PHP]防止XSS撰寫注意事項

[Javascript]彈跳視窗(alert、confirm、prompt)

One thought on “[Oauth]使用 OAuth 2.0 存取 Google APIs(for Login)

  1. Pingback: 使用 Facebook, Google+ 進行網站會員認證 | hoyo 學習紀錄

Comments are closed.