Currently, the person I'm developing for uses google docs to display the website/files. Which can only be accessed via google accounts ending in a certain domain name. For example [email protected] if it's a webtest google account then it can access it.
Now I'm creating them a website not linked to google. However, I still need this authentication process.
Step One login page will be a simple "connect with google account"
Step Two user is redirected to login to google, if they're already logged in then moves to next step.
Step three email address is crosschecked with my database, if there a session is made for the row id of that user, if not then it is added.
I'm trying to keep this as simple as possible, however I have no idea where or how to do step Two.
After reading the Wikipedia introduction mentioned by @Izzy, you can have a look at google's Oauth2 introduction and then jump into google's quick start sample app; it gives a fully working commented php app of using oauth 2.0 to authenticate with a google account and fetch user data.
The code in the example uses the package google-api-php-client as well as a js library to reduce the boilerplate to simpler API calls. For the client/frontend side, javascript calls such as:
auth2.signIn().then(function(googleUser) {
onSignInCallback(googleUser.getAuthResponse());
}, function(error) {
alert(JSON.stringify(error, undefined, 2));
});
And on the server, php side:
$code = $request->getContent();
// Exchange the OAuth 2.0 authorization code for user credentials.
$client->authenticate($code);
$token = json_decode($client->getAccessToken());
// You can read the Google user ID in the ID token.
// "sub" represents the ID token subscriber which in our case
// is the user ID. This sample does not use the user ID.
$attributes = $client->verifyIdToken($token->id_token, CLIENT_ID)
->getAttributes();
$gplus_id = $attributes["payload"]["sub"];
// Store the token in the session for later use.
$app['session']->set('token', json_encode($token));
$response = 'Successfully connected with token: ' . print_r($token, true);
Please note that requesting an email address will require asking further the permission (named Authorization scopes
) from the client, as seen in this SO question:
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
You can then use any number of APIs that expose userinfo.email. One of these, Google_Service_Oauth2
, has the helpful public method userinfo
$oauth2Service = new Google_Service_Oauth2(...);
$userinfo = $oauth2Service->userinfo;