oauthgithub.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. //demo https://aroz.alanyeung.co/oauth.php
  3. //please go to https://github.com/settings/applications/ to get the client_id and client_secret, pleae remind that the redirect_uri must be same as github.com
  4. $baselink = "https://github.com/login/oauth"; //do not change it
  5. // CHNAGE HERE
  6. $client_id = "8757b82f0e4c52d34ec8"; //Client ID
  7. $client_secret = "96cfe75be2a9ffb6b8fca3811d76ebef63a17bbd"; //Client Secret
  8. $redirect_uri = "https://aroz.alanyeung.co/AOB/oauthgithub.php"; //Authorization callback URL
  9. // CHANGE HERE
  10. if(isset($_GET["code"])){
  11. //we use the one time code ($_GET["code"]) to get the access_token
  12. $fields = array(
  13. 'grant_type' => 'authorization_code',
  14. 'client_id' => $client_id,
  15. 'client_secret' => $client_secret,
  16. 'redirect_uri' => $redirect_uri,
  17. 'code' => $_GET["code"],
  18. );
  19. $postvars = http_build_query($fields);
  20. $ch = curl_init();
  21. curl_setopt($ch, CURLOPT_URL, $baselink."/access_token");
  22. curl_setopt($ch, CURLOPT_POST, count($fields));
  23. curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
  24. curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
  25. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  26. 'Accept: application/json'
  27. ));
  28. $result = curl_exec($ch);
  29. curl_close($ch);
  30. $data = json_decode($result,true);
  31. //$data had access_token,token_type,scope inside, but only access_token needed.
  32. //print_r($data);
  33. //obtain the userinfo here due to github had their own OAuth implementions
  34. $chs = curl_init();
  35. curl_setopt($chs, CURLOPT_URL, "https://api.github.com/user");
  36. curl_setopt($chs,CURLOPT_RETURNTRANSFER, true);
  37. curl_setopt($chs, CURLOPT_HTTPHEADER, array(
  38. "Authorization: token ".$data["access_token"],
  39. "User-Agent: Test"
  40. ));
  41. $result = curl_exec($chs);
  42. curl_close($chs);
  43. $userinfo = json_decode($result,true);
  44. //print_r($userinfo);
  45. session_start();
  46. $_SESSION["login"] = $userinfo["login"];
  47. setcookie("username",$userinfo["login"],time()+ 172800 );
  48. setcookie("password","OAuthGithub",time()+ 172800 );
  49. echo '<script>localStorage.ArOZusername = "'.$userinfo["login"].'";window.location = "./index.php"</script>';
  50. }