oauthgithub.php 2.1 KB

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