-
Notifications
You must be signed in to change notification settings - Fork 53
OAuth token obtaining
Sending an OAuth token withing a request is one of the authentication ways. If you need a small amount of tokens, you can create them manually at Personal Access Tokens page. Click to Generate new token
, copy the token string and:
$token = new Milo\Github\OAuth\Token('.s.e.c.r.e.t.');
Following chapter describes a token obtaining by OAuth web flow.
Class Milo\Github\OAuth\Login helps you. Workflow to obtain the token in a short:
- you redirect user to GitHub web page
- user allows access for your application
- after agree-click, user is redirected back to your application with a code in URL
- you get the code and send a POST request to obtain a token
- you have the token
Let's obtain the token. At first, register your application at GitHub web site:
Account Settings
-> Developer settings
-> OAuth Apps
(New OAuth App)
There you get a $clientId
and $clientSecret
which you will need. Read about token scopes and let's code:
use Milo\Github;
session_start();
$config = new Github\OAuth\Configuration($clientId, $clientSecret, ['user', 'repo']);
$storage = new Github\Storages\SessionStorage; # default naive implementation
$login = new Github\OAuth\Login($config, $storage);
# Your application URL
$appUrl = 'https://my.application.tld/index.php';
# Token obtaining
if ($login->hasToken()) {
$token = $login->getToken();
} else {
if (isset($_GET['back'])) {
$token = $login->obtainToken($_GET['code'], $_GET['state']);
header("Location: $appUrl"); # drop the 'code' and 'state' from URL
die();
} else {
# Performs redirect to Github page
$login->askPermissions("$appUrl?back=1");
}
}
Example should be pretty straightforward but few notes:
-
Login::askPermissions()
performs the HTTP redirection and dies. If you wish, pass a callback as a 2nd argument and make redirection by your own. And don't forget to die(). -
Login class needs session to store a security information and the token. There is used the Milo\Github\Storages\SessionStorage class which is a very naive implementation. Implement your own storage by ISessionStorage if you wish.
-
The token is stored in a session storage. Drop it by
Login::dropToken()
if you wish.
Once you have a token, pass it to API. It will be used every GitHub API request.
$api = new Milo\Github\Api;
$api->setToken($token);