I am trying to authenticate a user using the php-github-api library. So far I have sent the user to Github to allow my application access and I successfully get a token back. I'm not sure what to do now. Here is my code.
The URL I send the user to Github with.
https://github.com/login/oauth/authorize?scope=repo,user&client_id=<client_id>
Then with the php-github-api I am doing this. The $token variable is the code that is sent in the $_GET array when the user is redirected to the callback.
$client = new \Github\Client();
try {
$auth = $client->authenticate($token, Github\Client::AUTH_HTTP_TOKEN);
} catch (Exception $e) {
dp($e);
}
Does anyone know if this is the correct method to authenticate a user? When I try and call a method the requires an authenicated user I get a 401 status code and an error in return.
Thanks in advance!
You can authenticate your request by adding a token. If you want to use the GitHub REST API for personal use, you can create a personal access token.
Authentication methods You have three options for authenticating with this API: OAuth2 Access Token. Client ID and Client Secret (confidential applications) Client ID (public applications)
Thanks everyone for their suggestions. Seems like you have to feed the access_token into the authenticate method so an easy fix I implemented was a CURL request to grab the access_token then adding it to the authenticate method in the callback.
$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());
}
Then in the call back we can call the authenticate method to and cache it somewhere, currently I am doing this in the session.
$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());
}
So there we have it.
I did try using the HttpClient of the php github api library but I was having some issues so chose a more simple solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With