-
Notifications
You must be signed in to change notification settings - Fork 53
OAuth token obtaining
Sending an OAuth token withing request is one of the authentication ways. Class Milo\Github\OAuth\Login helps you to obtain the token.
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 code in URL
- you get the code and send POST request to obtain the token
- you have the token
Let's obtain the token. At first, register your application at Github web site:
Account Settings
-> Applications
-> Developer applications
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\Config($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 2nd arguments and make redirection by your own. -
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 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);