PHP code example of bybrand / oauth2-microsoft

1. Go to this page and download the library: Download bybrand/oauth2-microsoft library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bybrand / oauth2-microsoft example snippets


use Bybrand\OAuth2\Client\Provider\Microsoft;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;

$provider = new Microsoft([
    'clientId'     => 'your-client-id',
    'clientSecret' => 'your-client-secret',
    'redirectUri'  => 'your-redirect-uri',
    'tenant'       => 'common', // common | organizations | consumers | tenant-id
]);

$params = $_GET;

if (!isset($params['code']) || empty($params['code'])) {
    $authorizationUrl = $provider->getAuthorizationUrl();
    $_SESSION['oauth2state'] = $provider->getState();

    header('Location: ' . $authorizationUrl);
    exit;
}

if (empty($params['state']) || ($params['state'] !== $_SESSION['oauth2state'])) {
    unset($_SESSION['oauth2state']);
    exit('Invalid state');
}

try {
    $token = $provider->getAccessToken('authorization_code', [
        'code' => $params['code']
    ]);

    $user = $provider->getResourceOwner($token);

    $id = $user->getId();
    $name = $user->getName();
    $email = $user->getEmail();
} catch (IdentityProviderException $e) {
    // Handle token/user request errors.
}