Skip to content

Instantly share code, notes, and snippets.

@nkkollaw
Last active December 2, 2017 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkkollaw/2286e2e14e6bf91f3843c8710274b99b to your computer and use it in GitHub Desktop.
Save nkkollaw/2286e2e14e6bf91f3843c8710274b99b to your computer and use it in GitHub Desktop.
Simple PHP example of using Github's OAuth 2 API
<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
define('GITHUB_APP_NAME', ''); // your Github username or application name (required by Github)
define('OAUTH2_CLIENT_ID', '');
define('OAUTH2_CLIENT_SECRET', '');
define('AUTHORIZE_URL', 'https://github.com/login/oauth/authorize');
define('TOKEN_URL', 'https://github.com/login/oauth/access_token');
define('API_URL_BASE', 'https://api.github.com/');
function api_request($url, $post=FALSE, $headers=array()) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, GITHUB_APP_NAME);
if ($post) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
}
$headers[] = 'Accept: application/json'; // required to return JSON
if (session('access_token')) {
$headers[] = 'Authorization: Bearer ' . session('access_token');
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
return json_decode($response, true);
}
function get($key, $default=NULL) {
return array_key_exists($key, $_GET) ? $_GET[$key] : $default;
}
function session($key, $default=NULL) {
return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;
}
session_start();
// Start the login process by sending the user to Github's authorization page
if (get('action') == 'login') {
unset($_SESSION['access_token']);
// Generate a random hash and store in the session for security
$_SESSION['state'] = hash('sha256', microtime(TRUE) . rand() . $_SERVER['REMOTE_ADDR']);
$params = array(
'client_id' => OAUTH2_CLIENT_ID,
'redirect_uri' => 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'],
'scope' => 'user',
'state' => $_SESSION['state']
);
// Redirect the user to Github's authorization page
header('Location: ' . AUTHORIZE_URL . '?' . http_build_query($params));
exit;
}
// When Github redirects the user back here, there will be a "code" and "state" parameter in the query string
if (get('code')) {
unset($_SESSION['access_token']);
// Verify the state matches our stored state
if (!get('state') || $_SESSION['state'] != get('state')) {
header('Location: ' . $_SERVER['PHP_SELF']);
exit;
}
// Exchange the auth code for a token
$token = api_request(TOKEN_URL, array(
'client_id' => OAUTH2_CLIENT_ID,
'client_secret' => OAUTH2_CLIENT_SECRET,
'redirect_uri' => 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'],
'state' => $_SESSION['state'],
'code' => get('code')
));
$_SESSION['access_token'] = $token['access_token'];
header('Location: ' . $_SERVER['PHP_SELF']);
exit;
}
if (session('access_token')) {
$user = api_request(API_URL_BASE . 'user');
if (empty($user['id'])) {
switch ($user['message']) {
case 'Bad credentials':
default:
// something went wrong, how to handle this? let's just bail
unset($_SESSION['access_token']);
header('Location: ' . $_SERVER['PHP_SELF']);
exit;
}
}
echo '<h3>Logged In</h3>';
echo '<h4>' . $user['name'] . '</h4>';
echo '<pre>';
print_r($user);
echo '</pre>';
} else {
echo '<h3>Not logged in</h3>';
echo '<p><a href="?action=login">Log In</a></p>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment