|
| 1 | +This package provides NinjaOne OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client). |
| 2 | + |
| 3 | +## Installation |
| 4 | + |
| 5 | +To install, use composer: |
| 6 | + |
| 7 | +``` |
| 8 | +composer require twetech/oauth2-ninjaone |
| 9 | +``` |
| 10 | + |
| 11 | + |
| 12 | +## Usage |
| 13 | + |
| 14 | +Usage is the same as The League's OAuth client, using `\League\OAuth2\Client\Provider\Ninjaone` as the provider. |
| 15 | + |
| 16 | +### Authorization Code Flow |
| 17 | + |
| 18 | +```php |
| 19 | +$provider = new League\OAuth2\Client\Provider\Snapchat([ |
| 20 | + 'clientId' => '{snapchat-client-id}', |
| 21 | + 'clientSecret' => '{snapchat-client-secret}', |
| 22 | + 'redirectUri' => 'https://example.com/callback-url' |
| 23 | +]); |
| 24 | + |
| 25 | +if (!isset($_GET['code'])) { |
| 26 | + |
| 27 | + // If we don't have an authorization code then get one |
| 28 | + $authUrl = $provider->getAuthorizationUrl(); |
| 29 | + $_SESSION['oauth2state'] = $provider->getState(); |
| 30 | + header('Location: '.$authUrl); |
| 31 | + exit; |
| 32 | + |
| 33 | +// Check given state against previously stored one to mitigate CSRF attack |
| 34 | +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { |
| 35 | + |
| 36 | + unset($_SESSION['oauth2state']); |
| 37 | + exit('Invalid state'); |
| 38 | + |
| 39 | +} else { |
| 40 | + |
| 41 | + // Try to get an access token (using the authorization code grant) |
| 42 | + $token = $provider->getAccessToken('authorization_code', [ |
| 43 | + 'code' => $_GET['code'] |
| 44 | + ]); |
| 45 | + |
| 46 | + // Optional: Now you have a token you can look up a users profile data |
| 47 | + try { |
| 48 | + |
| 49 | + // We got an access token, let's now get the user's details |
| 50 | + $user = $provider->getResourceOwner($token); |
| 51 | + |
| 52 | + // Use these details to create a new profile |
| 53 | + printf('Hello %s!', $user->getName()); |
| 54 | + |
| 55 | + } catch (Exception $e) { |
| 56 | + |
| 57 | + // Failed to get user details |
| 58 | + exit('Oh dear...'); |
| 59 | + } |
| 60 | + |
| 61 | + // Use this to interact with an API on the users behalf |
| 62 | + echo $token->getToken(); |
| 63 | +} |
| 64 | +``` |
0 commit comments