Authentication using GitHub API

Today’s article with authentication using GitHub API, Which helps you to Log In / Sign Up your application to collect user data. GitHub is a version control repository and Internet hosting service. It offers all of the distributed version control and source code management functionality of Git as well as adding its own features. It provides access control and several collaboration features such as bug tracking, feature requests, task management, and wikis for every project. Nowadays everyone using GitHub/Gist to maintain version control of their source code and also to share source code with their team members or public.

Steps to do authentication using GitHub API

  • Login to your GitHub
  • Go to Settings -> OAuth applications -> Register a new application
  • Enter your application name, description, URL and authorization callback URL
  • After registering your application on GitHub you will get the Client ID and Client Secret
  • Define your Client ID and Client Secret on our code
  • Now, Execute code to login/signup using GitHub


Note :
Authorization callback URL is the URL where your file is hosted, Its also the return URL from GitHub after authorization

Source Code (PHP)

<?php
define('OAUTH2_CLIENT_ID', '65be302e546d2d7b6851');
define('OAUTH2_CLIENT_SECRET', 'a0fb82d81d4bee07d683b7f395dc66818f72f9c2');
$authorizeURL = 'https://github.com/login/oauth/authorize';
$tokenURL = 'https://github.com/login/oauth/access_token';
$gitUserAPI = 'https://api.github.com/user';
session_start();

function apiRequest($url, $post=FALSE, $headers=array()) {
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  if($post)
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
  $headers[] = 'User-Agent: siva-sankar';
  $headers[] = 'Accept: application/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);
}

if( isset($_GET['action']) && $_GET['action'] == 'login') {
  $_SESSION['state'] = hash('sha256', microtime(TRUE).rand().$_SERVER['REMOTE_ADDR']);
  unset($_SESSION['access_token']);
  $params = array(
    'client_id' => OAUTH2_CLIENT_ID,
    'redirect_uri' => 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'],
    'scope' => 'user',
    'state' => $_SESSION['state']
  );
  header('Location: ' . $authorizeURL . '?' . http_build_query($params));
  die();
}

if(isset($_GET['code'])) {
  if(!$_GET['state'] || $_SESSION['state'] != $_GET['state']) {
    header('Location: ' . $_SERVER['PHP_SELF']);
    die();
  }
  $token = apiRequest($tokenURL, 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']);
}
?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Authentication using GitHub API (Log In / Sign Up)</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/font-awesome.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>

  <body>
    <div class="container">
      <?php
      if(isset($_SESSION['access_token'])) {
        $user = apiRequest($gitUserAPI);
        ?>
        <div class="githubDetails">
          <img src="<?php echo $user->avatar_url; ?>" alt="<?php echo $user->login; ?>" width="150" class="img-circle">
          <h2><?php echo $user->name; ?></h2>
          <h4>(<?php echo $user->login; ?>)</h4>
          <h5><?php echo $user->bio; ?></h5>
          <h5><?php echo $user->location; ?></h5>
          <ul class="social-network social-circle">
              <li><a href="<?php echo $user->html_url; ?>" target="_blank" class="github" title="github"><i class="fa fa-github"></i></a></li>
              <li><a href="<?php echo $user->blog; ?>" target="_blank" class="blog" title="blog"><i class="fa fa-globe"></i></a></li>
              <li><a href="mailto:<?php echo $user->email; ?>" target="_blank" class="mail" title="mail"><i class="fa fa-envelope"></i></a></li>
          </ul>
          <div class="profile-details">
            <dl class="dl-horizontal">
            <dt>Created :</dt>
            <dd><?php echo gmdate("F j, Y, g:i a", strtotime($user->created_at)); ?></dd>
            <dt>Last Activity :</dt>
            <dd><?php echo gmdate("F j, Y, g:i a", strtotime($user->updated_at)); ?></dd>
            <dt>Public Repositories :</dt>
            <dd><?php echo $user->public_repos; ?> <i>Repository</i></dd>
            <dt>Public Gists :</dt>
            <dd><?php echo $user->public_gists; ?> <i>Gist<i></dd>
            </dl>
          </div>
        </div>
        <?php } else { ?>
        <h2>Authentication using GitHub API</h2>
        <h4>(Log In / Sign Up)</h4>
        <a class="githubBtn" href="?action=login" id="oauth"> <i class="fa fa-github fa-lg"></i> Sign in via GitHub </a>
        <?php } ?>
    </div>
    <footer class="footer">
      <div class="container">
        <p class="text-muted">Copyright &copy; <a href="http://niralar.com/" target="_blank">Siva Sankar</a></p>
      </div>
    </footer>
  </body>
</html>

Download/Demo:

Demo Download

Please leave your valuable comments/suggestions/feedback on below comment box if any.

Thank You !!

Leave a Reply

Your email address will not be published. Required fields are marked *