-
Notifications
You must be signed in to change notification settings - Fork 1
/
authorization.php
69 lines (56 loc) · 2.25 KB
/
authorization.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
require_once __DIR__ . '/../../vendor/autoload.php';
use Jampire\OAuth2\Client\Provider\AppIdProvider;
use Jampire\OAuth2\Client\Provider\AppIdException;
session_start();
try {
$provider = new AppIdProvider([
'baseAuthUri' => '',
'tenantId' => '',
'clientId' => '',
'clientSecret' => '',
'redirectUri' => '',
]);
} catch (AppIdException $e) {
exit('Failed to create provider: ' . $e->getMessage());
}
if (!isset($_GET['code'])) {
// If we don't have an authorization code then get one
// Fetch the authorization URL from the provider; this returns the
// urlAuthorize option and generates and applies any necessary parameters
// (e.g. state).
$authorizationUrl = $provider->getAuthorizationUrl();
// Get the state generated for you and store it to the session.
$_SESSION['oauth2state'] = $provider->getState();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
}
if (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) {
// Check given state against previously stored one to mitigate CSRF attack
if (isset($_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
}
exit('Invalid state');
}
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// We have an access token, which we may use in authenticated
// requests against the service provider's API.
echo '<b>Access Token:</b> ', $accessToken->getToken(), '<br>';
echo '<b>Refresh Token:</b> ', $accessToken->getRefreshToken(), '<br>';
echo '<b>Expired in:</b> ', $accessToken->getExpires(), '<br>';
echo '<b>Already expired?</b> ', ($accessToken->hasExpired() ? 'expired' : 'not expired'), '<br>';
// Using the access token, we may look up details about the
// resource owner.
$resourceOwner = $provider->getResourceOwner($accessToken);
echo '<pre>';
var_export($resourceOwner->toArray());
echo '</pre>';
} catch (Exception $e) {
// Failed to get the access token or user details.
exit($e->getMessage());
}