认证后从github获取用户详细信息

时间:2018-12-01 01:52:01

标签: php github

我有一个登录页面,该页面将用户引向GitHub进行身份验证。 验证身份后,GitHub成功将代码和状态作为GET参数返回到我的登录页面。 获取access_token后是否可以获取GitHub用户的电子邮件,名称和句柄?

if(get('action') == 'login') 
    {
        // Generate a random hash and store in the session for security
        $_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']
        );
        // Redirect the user to Github's authorization page
        header('Location: ' . $authorizeURL . '?' . http_build_query($params));
        die();
    }

    // When Github redirects the user back here, there will be a "code" and "state" parameter in the query string
    if (get('code')) 
    {
        // Verify the state matches our stored state
        if (!get('state') || $_SESSION['state'] != get('state')) {
            header('Location: ' . $_SERVER['PHP_SELF']);
            die();
        }
        // Exchange the auth code for a token
      $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')
      ));
       echo var_dump($token) ."<br>";
      echo json_encode($token);
      $_SESSION['access_token'] = $token->access_token;
      header('Location: ' . $_SERVER['PHP_SELF']);
    }
  }


  function apiRequest($url, $post = FALSE, $headers = array())
  {
      $ch = curl_init($url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
      if ($post)
          curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
      $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);
  }

  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;
  }

1 个答案:

答案 0 :(得分:0)

您需要使用访问令牌调用Github API来访问当前用户

因此,如果您已经具有可用的access_token并将其成功保存在$_SESSION['access_token']中-它将自动用于apiRequest()方法调用完成的所有其他请求

$user = apiRequest("https://api.github.com/user');
var_dump($user);
// $user->name  should be available in response

当我测试您的代码时-apiRequest-Method返回一个错误(var_dump($response)

Request forbidden by administrative rules. Please make sure your request has a User-Agent header (http://developer.github.com/v3/#user-agent-required). Check https://developer.github.com for other possible causes.

只需将User-Agent添加到方法中的headers[]数组中(例如,在添加的Accept:标头的正下方)

$headers[] = 'User-Agent: PHP Api Call';

...,您的API调用将开始工作;)

编辑:因为您在初始Auth-Request中设置了'scope' => 'user',-您请求访问用户数据-但仅此而已(如果需要其他权限/信息,请参见OAuth-App-Scopes