Skip to content

Instantly share code, notes, and snippets.

@m-manu
Last active January 3, 2016 20:38
Show Gist options
  • Save m-manu/8515837 to your computer and use it in GitHub Desktop.
Save m-manu/8515837 to your computer and use it in GitHub Desktop.
Switch from your custom implementation of authentication (storing usernames and passwords in your data store) to a "Login using Google" in no-time. Below is an ultra-light authorization using Google OAuth 2.0. Visit https://cloud.google.com/console/project >> APIs & auth >> Credentials
<?php
define('GOOGLE_OAUTH2_CLIENT_ID', 'client id'); // this will be of form "<number>.apps.googleusercontent.com"
define('GOOGLE_OAUTH2_CLIENT_SECRET', 'client secret'); // this will be a base64 string
define('GOOGLE_OAUTH2_REDIRECT_URI', 'redirect url'); // This URL should be registered under "Redirect URIs"
define('YOUR_DOMAIN', 'your domain'); // your domain
define('OAUTH2_SESSION_DURATION', 90); //in seconds
require __DIR__ . "/url_get_contents.php"; // Use https://gist.github.com/m-manu/7462652
function getGoogleOAuthRedirectUrl($redirect_uri) {
$required_permissions = array("https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile");
$google_auth_url = "https://accounts.google.com/o/oauth2/auth?" . http_build_query(array(
"redirect_uri" => $redirect_uri,
"response_type" => "code",
"client_id" => GOOGLE_OAUTH2_CLIENT_ID,
"scope" => implode(' ', $required_permissions),
"approval_prompt" => "force",
"access_type" => "offline",
));
return $google_auth_url;
}
function redirect($url) {
header("Location: $url");
echo "<script type=\"text/javascript\">\nwindow.location.href = \"" . addslashes($url) . "\";\n</script>\n";
exit;
}
if (isset($_REQUEST['code'])) {
$code = $_REQUEST['code'];
$response_token_rawstr = url_get_contents("https://accounts.google.com/o/oauth2/token", array(
"code" => $code,
"client_id" => GOOGLE_OAUTH2_CLIENT_ID,
"client_secret" => GOOGLE_OAUTH2_CLIENT_SECRET,
"redirect_uri" => GOOGLE_OAUTH2_REDIRECT_URI,
"grant_type" => "authorization_code")
, 'POST');
$response_token = json_decode($response_token_rawstr, true);
if (isset($response_token['access_token'])) {
$token = $response_token['access_token'];
$response_userinfo_rawstr = url_get_contents("https://www.googleapis.com/userinfo/v2/me", array('access_token' => $token));
$response_userinfo = json_decode($response_userinfo_rawstr, true);
setcookie('GOOGLE_OAUTH2', serialize($response_userinfo), time() + OAUTH2_SESSION_DURATION, '/', YOUR_DOMAIN);
redirect($_COOKIE['url_goback']);
}
else {
error_log("Google didn't return an access token for code \"$code\"");
die("<h1>Login error</h1>");
}
}
else {
error_log("No parameter 'code' received");
setcookie('url_goback', $_REQUEST['url_goback'], time() + 10);
redirect(getGoogleOAuthRedirectUrl(GOOGLE_OAUTH2_REDIRECT_URI));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment