G Suite OpenId connection for personnal web application - php

I want to implement OpenId of G Suite api to connect the user of my own php application and use the G Suite manage of user.
So I have write the example below :
in index.php I have load autoload.php (with google-api-php-client library)
$client = new \Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(SECRET);
$client->setAuthConfig(ROOT_PATH.CLIENT_SECRET_JSON_FILE);
$client->setAccessType("offline");
$client->setIncludeGrantedScopes(true);
$client->setHostedDomain('mydomain.com');
$client->addScope(\Google_Service_Oauth2::USERINFO_PROFILE);
$redirect = $_SERVER['HTTP_HOST'];
$redirect = 'myapplication.mydomain.com';
$client->setRedirectUri('https://' . $redirect . '/oauth2callback.php');
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
oauth2callback.php
$client = new \Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(SECRET);
$client->setAuthConfig(ROOT_PATH.CLIENT_SECRET_JSON_FILE);
$client->setRedirectUri('https://myapplication.mydomain.com/oauth2callback.php');
$client->setAccessType("offline");
$client->setIncludeGrantedScopes(true);
$client->setHostedDomain('mydomain.com');
if (!isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
}
else {
$client->fetchAccessTokenWithAuthCode($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$oauth = new \Google_Service_Oauth2($client);
var_dump($oauth->userinfo->get());
}
exit();
All is ok with this example, but, I can connect on my application with another account of my G Suite domain :-(
I don't understand where I must configure it to authorize only the user of my G Suite domain to access at my application.
Can you help me ?
Thanks

I have a start of answer, it's impossible.
But, with the return of api, it's possible to check the value hd (hosted domain) to compare it with my. https://developers.google.com/identity/sign-in/web/backend-auth
In my case, I haven't return value of hd :-( and I don't why

I have found the solution :-)
It's simple. The scope must be "email". If there is this value, Gsuite return automatically value in hd to check it.
After the return, I juste test the value to compare with my Gsuite domain :-)

Related

Google API and OAuth 2.0

I'm trying to use google calendar API with php library and i'm facing issues on the authentification of the user to the google api.
I have a question. I've seen some come where you had to set the Api key / developer key to the Google_Client object with the method setDeveloperKey(), but i've also seen some people who don't. Could someone explain to me what difference does it make ?
The thing i'd like to do is to connect a user who have a google account to my application so he can add, list, remove, etc, events from a calendar. This is what i'm doing for the moment for the authentification :
$client = new Google_Client();
$client->setApplicationName("Test GCAL");
$client->setClientId($clientid);
$client->setClientSecret($clientsecret);
$client->setRedirectUri($callback_url);
$client->setAccessType("offline");
$client->setApprovalPrompt("force");
$client->setScopes("https://www.googleapis.com/auth/calendar");
$service = new Google_Service_Calendar($client);
Am i doing it right ?
Does someone have a working commented code that i can analyse ? I can't find one that's working on the internet.. Or maybe a tutorial that explain everything about google api and oauth stuff. I'm so confused about tokens and nobody seems to use refresh tokens, and to me that's essential.. But maybe i'm wrong ?
Thanks for your answers
I don't think you NEED to use setDeveloperKey I suspect that its only used for public APIs to enable you to use them but I haven't really tested it or thought about it before. I will have to look into that a bit more.
This is the code I use for connecting to Google Calendar with Oauth2. ripped directly from the Accessing Google Calendar with PHP – Oauth2 tutorial
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
require_once 'CalendarHelper.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("AIzaSyBBH88dIQPjcl5nIG-n1mmuQ12J7HThDBE");
$client->setClientId('2046123799103-i6cjd1hkjntu5bkdkjj5cdnpcu4iju8p.apps.googleusercontent.com');
$client->setClientSecret('6s4YOx3upyJhtwnetovfK40e');
$client->setRedirectUri('http://localhost/google-api-php-client-samples/Calendar/oauth2Pure.php');
$client->setAccessType('offline'); // Gets us our refreshtoken
$client->setScopes(array('https://www.googleapis.com/auth/calendar.readonly'));
//For loging out.
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$service = new Google_Service_Calendar($client);
$calendarList = $service->calendarList->listCalendarList();;
print_r($calendarList);
while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo $calendarListEntry->getSummary()."<br>\n";
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
}
?>

google api calendar php

I am aware many similar questions have been asked, but I am struggling to understand. I have successfully used the php google libraries for v3 to interface with calendar functions. The code I have is:
<?php
require_once "google-api-php-client/autoload.php";
session_start();
$client = new Google_Client();
$client->setApplicationName("My app");
$client->setClientId("CI.apps.googleusercontent.com");
$client->SetClientSecret("SECRET");
$client->setRedirectUri("redirect");
$client->setDeveloperKey("key");
$client->setScopes(array("https://www.googleapis.com/auth/calendar"));
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);//update token
}
$service=new Google_Service_Calendar($client);
...
?>
This works ok, but the calendar I want to modify is always the same- the app is registered at the same account as the calendar. Is there a way round the oauth2 authentication so that I can just adjust the entries in the calendar which I own without having to perform an extra authentication step with redirect? I used to use Zend to do this and it worked fine until recently, but updating to v3 of the API and using oauth2 like this seems a bit overkill. I may have misunderstood of course - any help of advice would me most helpful.
Ok - in case anyone else searches for the answer to this I thought I'd post my solution. I was a bit stupid. If you want to authenticate an application to modify a calendar in this way you need to create a service account in the google console - not a web application. Then you need to use the service account name (e-mail address given to the Client ID for the service account) to allow the script to modify the calendar. Do this manually by going to the setting of the calendar you want to modify. This code will then work fine.
<?php
session_start();
require_once "google-api-php-client/autoload.php";
$client_id = ''; //Client ID
$service_account_name = ''; //Email Address
$key_file_location = ''; //key.p12
$client = new Google_Client();
$client->setApplicationName("my app");
$service = new Google_Service_Calendar($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar'),
$key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();?>

Using Codenvy to OAuth Google with php

I am fairly new to codenvy and php but I have doublechecked the following, yet I am still not asked to oauth into google when I launch this with the following code. I followed instructions from here. any obvious mistakes in the below?
https://developers.google.com/analytics/solutions/articles/hello-analytics-api
<?php
require_once 'src/Google/Client.php';
require_once 'src/Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName('Hello Analytics API Sample');
// Visit https://console.developers.google.com/ to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('CONFIRMED THIS IS CORRECT');
$client->setClientSecret('CONFIRMED THIS IS CORRECT');
$client->setRedirectUri('https://codenvycorp.com/api/oauth/callback');
$client->setDeveloperKey('CONFIRMED THIS IS CORRECT');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
// Magic. Returns objects from the Analytics Service instead of associative arrays.
$client->setUseObjects(true);
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));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken()) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
$analytics = new apiAnalyticsService($client);
runMainDemo($analytics);
}
echo 'Hello World 321';
?>
If your project is public, please, share it with Codenvy's factory feature. So everyone will be able to look what is wrong with OAuth integration.
(You can access factory on left panel of the IDE)

Unable to get the refresh_token from google Oauth response

I am new to google client auth. I am trying to upload a file to my google drive using this php google client downloaded from here https://github.com/google/google-api-php-client
public function oauth2callback(){
set_include_path(get_include_path() . PATH_SEPARATOR . ROOT .DS. "vendors");
require_once 'Google/Client.php';
$client = new Google_Client();
$client->setClientId('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
$client->setClientSecret('xxxxxxxxxxxxxxxxx');
$client->setRedirectUri('http://example.com/auth/oauth2callback');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$client->setState('offline');
$authUrl = $client->createAuthUrl();
if (isset($_GET['code'])) {
$authCode = trim($_GET['code']);
$accessToken = $client->authenticate($authCode);
print_r($accessToken);
$client->setAccessToken($accessToken);
}
if ($client->getAccessToken()) {
// To do
}else{
$authUrl = $client->createAuthUrl();
echo "<a href='$authUrl'>Login Now</a>";
}
}
In the response, i only recieve this
{"access_token":"ya29.eQAeXvi4c5CAGRwAAAAKr55Tljr6z_GpdfjyY0xbrD15XGikNRL-D724Hx1L_g","token_type":"Bearer","expires_in":3600,"created":1410085058}
without any refresh token.
I just want to get the refresh token from the response for later use.
I also followed this question
Set the state to offline, revoked all the previous access that belonged to this app,
even tried with fresh new account/apps.. but never received refresh token..
Please guys help me out...
I was missing the access_type=offline..
So, adding
$client->setAccessType('offline');
fixed the problem.

Insert Moment in Google+ using Google PHP Client

I'm trying to insert some activity app in a Google+ profile as shown in this documentation page:
https://developers.google.com/+/api/latest/moments/insert
I successfully obtain the access token needed, but seems the moments->insert method doesn't make anything.
If successful I would expect to see something on this page, once made the access, but nothing happen
https://plus.google.com/u/0/apps/activities
That's my code
<?php
require_once '../google-api-php-client/Google_Client.php';
require_once '../google-api-php-client/contrib/Google_PlusService.php';
session_start();
$client = new Google_Client();
$client->setClientId('xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxxxxx');
$client->setRedirectUri('http://www.myregisteredcallbackurl.com');
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/plus.login'));
$client->setApprovalPrompt('force');
$plus = new Google_PlusService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
echo 'Logout<br><br>'.PHP_EOL.PHP_EOL;
$client->setAccessToken($_SESSION['token']);
$moment = new Google_Moment();
$moment->setType('http://schemas.google.com/AddActivity');
$itemScope = new Google_ItemScope();
$itemScope->setUrl('https://developers.google.com/+/plugins/snippet/examples/thing');
$moment->setTarget($itemScope);
$plus->moments->insert('me', 'vault', $moment);
}
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
echo 'Connect<br>';
}
You need to add the requestvisibleactions permissions to your scope. The easiest way to do this is to switch from the conventional OAuth 2.0 flow to the new Google+ Sign-In flow - the Google+ team provides a PHP sample for Google+ Sign-In. If you want to continue using the older OAuth flow, you need to append request_visible_actions=[the app activity types] to your authorization URL.
Related questions:
Google+ PHP moments not working
Google+ Insert moment using dot-net-client
Google+ unable to insert moment
In your code, you are really close, the following seems to work for me:
$client = new Google_Client();
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('http://example.com/callback.php');
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/plus.login'));
$client->setRequestVisibleActions(array('https://schemas.google.com/AddActivity'));
$plus = new Google_PlusService($client);
To check the app activities that you have written, visit the app activity log.

Categories