Dav*_*nes 19 php github github-api
我正在尝试使用php-github-api库对用户进行身份验证.到目前为止,我已经将用户发送到Github以允许我的应用程序访问,并且我成功获得了令牌.我不知道现在该做什么.这是我的代码.
我将用户发送给Github的URL.
https://github.com/login/oauth/authorize?scope=repo,user&client_id=<client_id>
Run Code Online (Sandbox Code Playgroud)
然后用php-github-api我这样做.$ token变量是当用户重定向到回调时在$ _GET数组中发送的代码.
$client = new \Github\Client();
try {
$auth = $client->authenticate($token, Github\Client::AUTH_HTTP_TOKEN);
} catch (Exception $e) {
dp($e);
}
Run Code Online (Sandbox Code Playgroud)
有谁知道这是否是验证用户的正确方法?当我尝试调用一个方法需要一个认证用户时,我得到一个401状态代码并返回一个错误.
提前致谢!
谢谢大家的建议.好像你必须将access_token提供给authenticate方法,所以我实现的一个简单的修复是一个CURL请求来获取access_token然后将它添加到回调中的authenticate方法.
$token = $_POST['token'];
$params = [
'client_id' => self::$_clientID,
'client_secret' => self::$_clientSecret,
'redirect_uri' => 'url goes here',
'code' => $token,
];
try {
$ch = curl_init('https://github.com/login/oauth/access_token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
$headers[] = 'Accept: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
} catch (\Exception $e) {
dp($e->getMessage());
}
Run Code Online (Sandbox Code Playgroud)
然后在回调中我们可以调用authenticate方法并将其缓存到某个地方,目前我在会话中这样做.
$client = self::getClient();
$_SESSION['access_token'] = $response->access_token;
try {
$client->authenticate($response->access_token, Github\Client::AUTH_HTTP_TOKEN);
} catch (\Exception $e) {
dp($e->getMessage());
}
Run Code Online (Sandbox Code Playgroud)
因此,我们有它.
我确实尝试使用php github api库的HttpClient,但我遇到了一些问题所以选择了一个更简单的解决方案.