PHPackages                             jdehais/oauth2-azure - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. jdehais/oauth2-azure

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

jdehais/oauth2-azure
====================

Azure Active Directory OAuth 2.0 Client Provider for The PHP League OAuth2-Client

2.1.2(2y ago)01.0kMITPHPPHP ^7.1|^8.0

Since Jul 26Pushed 2y agoCompare

[ Source](https://github.com/jdehais/oauth2-azure)[ Packagist](https://packagist.org/packages/jdehais/oauth2-azure)[ RSS](/packages/jdehais-oauth2-azure/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (3)Versions (2)Used By (0)

Azure Active Directory Provider for OAuth 2.0 Client
====================================================

[](#azure-active-directory-provider-for-oauth-20-client)

[![Latest Version](https://camo.githubusercontent.com/1e1b45c3a2e5587fe31058e4cc0c4d6be9ef38942738347d0498288e539ec1e2/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f7468656e6574776f72672f6f61757468322d617a7572652e7376673f7374796c653d666c61742d737175617265)](https://github.com/thenetworg/oauth2-azure/releases)[![Total Downloads](https://camo.githubusercontent.com/c08bb6f825ac6e6d3f2b8842729fb9857ad122d9b3471c52f005b888b0e8c7bb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7468656e6574776f72672f6f61757468322d617a7572652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/thenetworg/oauth2-azure)[![Software License](https://camo.githubusercontent.com/6926dd8687cc54f87efc7d40b9b78e102d766a72cfd877b11e32b3d8e63abc1d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f7468656e6574776f72672f6f61757468322d617a7572652e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)

This package provides [Azure Active Directory](https://azure.microsoft.com/en-us/services/active-directory/) OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client).

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Usage](#usage)
    - [Authorization Code Flow](#authorization-code-flow)
        - [Advanced flow](#advanced-flow)
        - [Using custom parameters](#using-custom-parameters)
        - [**NEW** - Call on behalf of a token provided by another app](#call-on-behalf-of-a-token-provided-by-another-app)
    - [**NEW** - Logging out](#logging-out)
- [Making API Requests](#making-api-requests)
    - [Variables](#variables)
- [Resource Owner](#resource-owner)
- [**UPDATED** - Microsoft Graph](#microsoft-graph)
- [**NEW** - Protecting your API - *experimental*](#protecting-your-api---experimental)
- [Azure Active Directory B2C - *experimental*](#azure-active-directory-b2c---experimental)
- [Multipurpose refresh tokens - *experimental*](#multipurpose-refresh-tokens---experimental)
- [Known users](#known-users)
- [Contributing](#contributing)
- [Credits](#credits)
- [Support](#support)
- [License](#license)

Installation
------------

[](#installation)

To install, use composer:

```
composer require thenetworg/oauth2-azure

```

Usage
-----

[](#usage)

Usage is the same as The League's OAuth client, using `\TheNetworg\OAuth2\Client\Provider\Azure` as the provider.

### Authorization Code Flow

[](#authorization-code-flow)

```
$provider = new TheNetworg\OAuth2\Client\Provider\Azure([
    'clientId'          => '{azure-client-id}',
    'clientSecret'      => '{azure-client-secret}',
    'redirectUri'       => 'https://example.com/callback-url',
    //Optional using key pair instead of secret
    'clientCertificatePrivateKey' => '{azure-client-certificate-private-key}',
    //Optional using key pair instead of secret
    'clientCertificateThumbprint' => '{azure-client-certificate-thumbprint}',
    //Optional
    'scopes'            => ['openid'],
    //Optional
    'defaultEndPointVersion' => '2.0'
]);

// Set to use v2 API, skip the line or set the value to Azure::ENDPOINT_VERSION_1_0 if willing to use v1 API
$provider->defaultEndPointVersion = TheNetworg\OAuth2\Client\Provider\Azure::ENDPOINT_VERSION_2_0;

$baseGraphUri = $provider->getRootMicrosoftGraphUri(null);
$provider->scope = 'openid profile email offline_access ' . $baseGraphUri . '/User.Read';

if (isset($_GET['code']) && isset($_SESSION['OAuth2.state']) && isset($_GET['state'])) {
    if ($_GET['state'] == $_SESSION['OAuth2.state']) {
        unset($_SESSION['OAuth2.state']);

        // Try to get an access token (using the authorization code grant)
        /** @var AccessToken $token */
        $token = $provider->getAccessToken('authorization_code', [
            'scope' => $provider->scope,
            'code' => $_GET['code'],
        ]);

        // Verify token
        // Save it to local server session data

        return $token->getToken();
    } else {
        echo 'Invalid state';

        return null;
    }
} else {
    // // Check local server's session data for a token
    // // and verify if still valid
    // /** @var ?AccessToken $token */
    // $token = // token cached in session data, null if not found;
    //
    // if (isset($token)) {
    //    $me = $provider->get($provider->getRootMicrosoftGraphUri($token) . '/v1.0/me', $token);
    //    $userEmail = $me['mail'];
    //
    //    if ($token->hasExpired()) {
    //        if (!is_null($token->getRefreshToken())) {
    //            $token = $provider->getAccessToken('refresh_token', [
    //                'scope' => $provider->scope,
    //                'refresh_token' => $token->getRefreshToken()
    //            ]);
    //        } else {
    //            $token = null;
    //        }
    //    }
    //}
    //
    // If the token is not found in
    // if (!isset($token)) {
        $authorizationUrl = $provider->getAuthorizationUrl(['scope' => $provider->scope]);

        $_SESSION['OAuth2.state'] = $provider->getState();

        header('Location: ' . $authorizationUrl);

        exit;
    // }

    return $token->getToken();
}
```

#### Advanced flow

[](#advanced-flow)

The [Authorization Code Grant Flow](https://msdn.microsoft.com/en-us/library/azure/dn645542.aspx) is a little bit different for Azure Active Directory. Instead of scopes, you specify the resource which you would like to access - there is a param `$provider->authWithResource` which will automatically populate the `resource` param of request with the value of either `$provider->resource` or `$provider->urlAPI`. This feature is mostly intended for v2.0 endpoint of Azure AD (see more [here](https://docs.microsoft.com/en-us/azure/active-directory/develop/azure-ad-endpoint-comparison#scopes-not-resources)).

#### Using custom parameters

[](#using-custom-parameters)

With [oauth2-client](https://github.com/thephpleague/oauth2-client) of version 1.3.0 and higher, it is now possible to specify custom parameters for the authorization URL, so you can now make use of options like `prompt`, `login_hint` and similar. See the following example of obtaining an authorization URL which will force the user to reauthenticate:

```
$authUrl = $provider->getAuthorizationUrl([
    'prompt' => 'login'
]);
```

You can find additional parameters [here](https://msdn.microsoft.com/en-us/library/azure/dn645542.aspx).

#### Using a certificate key pair instead of the shared secret

[](#using-a-certificate-key-pair-instead-of-the-shared-secret)

- Generate a key pair, e.g. with:

```
openssl genrsa -out private.key 2048
openssl req -new -x509 -key private.key -out publickey.cer -days 365
```

- Upload the `publickey.cer` to your app in the Azure portal
- Note the displayed thumbprint for the certificate (it looks like `B4A94A83092455AC4D3AC827F02B61646EAAC43D`)
- Put that thumbprint into the `clientCertificateThumbprint` constructor option
- Put the contents of `private.key` into the `clientCertificatePrivateKey` constructor option
- You can omit the `clientSecret` constructor option

### Logging out

[](#logging-out)

If you need to quickly generate a logout URL for the user, you can do following:

```
// Assuming you have provider properly initialized.
$post_logout_redirect_uri = 'https://www.msn.com'; // The logout destination after the user is logged out from their account.
$logoutUrl = $provider->getLogoutUrl($post_logout_redirect_uri);
header('Location: '.$logoutUrl); // Redirect the user to the generated URL
```

#### Call on behalf of a token provided by another app

[](#call-on-behalf-of-a-token-provided-by-another-app)

```
// Use token provided by the other app
// Make sure the other app mentioned this app in the scope when requesting the token
$suppliedToken = '';

$provider = xxxxx;// Initialize provider

// Call this to get claims
// $claims = $provider->validateAccessToken($suppliedToken);

/** @var AccessToken $token */
$token = $provider->getAccessToken('jwt_bearer', [
    'scope' => $provider->scope,
    'assertion' => $suppliedToken,
    'requested_token_use' => 'on_behalf_of',
]);
```

Making API Requests
-------------------

[](#making-api-requests)

This library also provides easy interface to make it easier to interact with [Azure Graph API](https://msdn.microsoft.com/en-us/library/azure/hh974476.aspx) and [Microsoft Graph](http://graph.microsoft.io), the following methods are available on `provider` object (it also handles automatic token refresh flow should it be needed during making the request):

- `get($ref, $accessToken, $headers = [])`
- `post($ref, $body, $accessToken, $headers = [])`
- `put($ref, $body, $accessToken, $headers = [])`
- `delete($ref, $body, $accessToken, $headers = [])`
- `patch($ref, $body, $accessToken, $headers = [])`
- `getObjects($tenant, $ref, $accessToken, $headers = [])` This is used for example for listing large amount of data - where you need to list all users for example - it automatically follows `odata.nextLink` until the end.
    - `$tenant` tenant has to be provided since the `odata.nextLink` doesn't contain it.
- `request($method, $ref, $accessToken, $options = [])` See [\#36](https://github.com/TheNetworg/oauth2-azure/issues/36) for use case.

*Please note that if you need to create a custom request, the method getAuthenticatedRequest and getResponse can still be used.*

### Variables

[](#variables)

- `$ref` The URL reference without the leading `/`, for example `myOrganization/groups`
- `$body` The contents of the request, make has to be either string (so make sure to use `json_encode` to encode the request)s or stream (see [Guzzle HTTP](http://docs.guzzlephp.org/en/latest/request-options.html#body))
- `$accessToken` The access token object obtained by using `getAccessToken` method
- `$headers` Ability to set custom headers for the request (see [Guzzle HTTP](http://docs.guzzlephp.org/en/latest/request-options.html#headers))

Resource Owner
--------------

[](#resource-owner)

With version 1.1.0 and onward, the Resource Owner information is parsed from the JWT passed in `access_token` by Azure Active Directory. It exposes few attributes and one function.

**Example:**

```
$resourceOwner = $provider->getResourceOwner($token);
echo 'Hello, '.$resourceOwner->getFirstName().'!';
```

The exposed attributes and function are:

- `getId()` - Gets user's object id - unique for each user
- `getFirstName()` - Gets user's first name
- `getLastName()` - Gets user's family name/surname
- `getTenantId()` - Gets id of tenant which the user is member of
- `getUpn()` - Gets user's User Principal Name, which can be also used as user's e-mail address
- `claim($name)` - Gets any other claim (specified as `$name`) from the JWT, full list can be found [here](https://azure.microsoft.com/en-us/documentation/articles/active-directory-token-and-claims/)

Microsoft Graph
---------------

[](#microsoft-graph)

Calling [Microsoft Graph](http://graph.microsoft.io/) is very simple with this library. After provider initialization simply change the API URL followingly (replace `v1.0` with your desired version):

```
// Mention Microsoft Graph scope when initializing the provider
$baseGraphUri = $provider->getRootMicrosoftGraphUri(null);
$provider->scope = 'your scope ' . $baseGraphUri . '/User.Read';

// Call a query
$provider->get($provider->getRootMicrosoftGraphUri($token) . '/v1.0/me', $token);
```

After that, when requesting access token, refresh token or so, provide the `resource` with value `https://graph.microsoft.com/` in order to be able to make calls to the Graph (see more about `resource` [here](#advanced-flow)).

Protecting your API - *experimental*
------------------------------------

[](#protecting-your-api---experimental)

With version 1.2.0 you can now use this library to protect your API with Azure Active Directory authentication very easily. The Provider now also exposes `validateAccessToken(string $token)` which lets you pass an access token inside which you for example received in the `Authorization` header of the request on your API. You can use the function followingly (in vanilla PHP):

```
// Assuming you have already initialized the $provider

// Obtain the accessToken - in this case, we are getting it from Authorization header
$headers = getallheaders();
// Assuming you got the value of Authorization header as "Bearer [the_access_token]" we parse it
$authorization = explode(' ', $headers['Authorization']);
$accessToken = $authorization[1];

try {
    $claims = $provider->validateAccessToken($accessToken);
} catch (Exception $e) {
    // Something happened, handle the error
}

// The access token is valid, you can now proceed with your code. You can also access the $claims as defined in JWT - for example roles, group memberships etc.
```

You may also need to access some other resource from the API like the Microsoft Graph to get some additional information. In order to do that, there is `urn:ietf:params:oauth:grant-type:jwt-bearer` grant available ([RFC](https://tools.ietf.org/html/draft-jones-oauth-jwt-bearer-03)). An example (assuming you have the code above working and you have the required permissions configured correctly in the Azure AD application):

```
$graphAccessToken = $provider->getAccessToken('jwt_bearer', [
    'resource' => 'https://graph.microsoft.com/v1.0/',
    'assertion' => $accessToken,
    'requested_token_use' => 'on_behalf_of'
]);

$me = $provider->get('https://graph.microsoft.com/v1.0/me', $graphAccessToken);
print_r($me);
```

Just to make it easier so you don't have to remember entire name for `grant_type` (`urn:ietf:params:oauth:grant-type:jwt-bearer`), you just use short `jwt_bearer` instead.

Azure Active Directory B2C - *experimental*
-------------------------------------------

[](#azure-active-directory-b2c---experimental)

You can also now very simply make use of [Azure Active Directory B2C](https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-reference-oauth-code/). Before authentication, change the endpoints using `pathAuthorize`, `pathToken` and `scope` and additionally specify your [login policy](https://azure.microsoft.com/en-gb/documentation/articles/active-directory-b2c-reference-policies/). **Please note that the B2C support is still experimental and wasn't fully tested.**

```
$provider->pathAuthorize = "/oauth2/v2.0/authorize";
$provider->pathToken = "/oauth2/v2.0/token";
$provider->scope = ["idtoken"];

// Specify custom policy in our authorization URL
$authUrl = $provider->getAuthorizationUrl([
    'p' => 'b2c_1_siup'
]);
```

Multipurpose refresh tokens - *experimental*
--------------------------------------------

[](#multipurpose-refresh-tokens---experimental)

In cause that you need to access multiple resources (like your API and Microsoft Graph), you can use multipurpose [refresh tokens](https://msdn.microsoft.com/en-us/library/azure/dn645538.aspx). Once obtaining a token for first resource, you can simply request another token for different resource like so:

```
$accessToken2 = $provider->getAccessToken('refresh_token', [
    'refresh_token' => $accessToken1->getRefreshToken(),
    'resource' => 'http://urlOfYourSecondResource'
]);
```

At the moment, there is one issue: When you make a call to your API and the token has expired, it will have the value of `$provider->urlAPI` which is obviously wrong for `$accessToken2`. The solution is very simple - set the `$provider->urlAPI` to the resource which you want to call. This issue will be addressed in future release. **Please note that this is experimental and wasn't fully tested.**

Known users
-----------

[](#known-users)

If you are using this library and would like to be listed here, please let us know!

- [TheNetworg/DreamSpark-SSO](https://github.com/thenetworg/dreamspark-sso)

Contributing
------------

[](#contributing)

We accept contributions via [Pull Requests on Github](https://github.com/thenetworg/oauth2-azure).

Credits
-------

[](#credits)

- [Jan Hajek](https://github.com/hajekj) ([TheNetw.org](https://thenetw.org))
- [Vittorio Bertocci](https://github.com/vibronet) (Microsoft)
    - Thanks for the splendid support while implementing #16
- [Martin Cetkovský](https://github.com/mcetkovsky) ([cetkovsky.eu](https://www.cetkovsky.eu)\]
- [All Contributors](https://github.com/thenetworg/oauth2-azure/contributors)

Support
-------

[](#support)

If you find a bug or encounter any issue or have a problem/question with this library please create a [new issue](https://github.com/TheNetworg/oauth2-azure/issues).

License
-------

[](#license)

The MIT License (MIT). Please see [License File](https://github.com/thenetworg/oauth2-azure/blob/master/LICENSE) for more information.

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity16

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 63.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

1021d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/04962fb544956f82229aa3bba6dff630f0bbc1c287156ed17558cd9c3e74109f?d=identicon)[cyllene-web](/maintainers/cyllene-web)

---

Top Contributors

[![hajekj](https://avatars.githubusercontent.com/u/8337913?v=4)](https://github.com/hajekj "hajekj (96 commits)")[![BertVM52](https://avatars.githubusercontent.com/u/34281226?v=4)](https://github.com/BertVM52 "BertVM52 (12 commits)")[![arueckauer](https://avatars.githubusercontent.com/u/1815979?v=4)](https://github.com/arueckauer "arueckauer (9 commits)")[![philipdaveby](https://avatars.githubusercontent.com/u/73835849?v=4)](https://github.com/philipdaveby "philipdaveby (4 commits)")[![sadika9](https://avatars.githubusercontent.com/u/2670029?v=4)](https://github.com/sadika9 "sadika9 (3 commits)")[![coolhome](https://avatars.githubusercontent.com/u/700740?v=4)](https://github.com/coolhome "coolhome (3 commits)")[![jdehais](https://avatars.githubusercontent.com/u/38524580?v=4)](https://github.com/jdehais "jdehais (3 commits)")[![stevenmaguire](https://avatars.githubusercontent.com/u/1851973?v=4)](https://github.com/stevenmaguire "stevenmaguire (2 commits)")[![spackmat](https://avatars.githubusercontent.com/u/185854?v=4)](https://github.com/spackmat "spackmat (2 commits)")[![Koenvh1](https://avatars.githubusercontent.com/u/5168825?v=4)](https://github.com/Koenvh1 "Koenvh1 (2 commits)")[![JoshuaBehrens](https://avatars.githubusercontent.com/u/1133593?v=4)](https://github.com/JoshuaBehrens "JoshuaBehrens (1 commits)")[![kojot1234](https://avatars.githubusercontent.com/u/348236?v=4)](https://github.com/kojot1234 "kojot1234 (1 commits)")[![krothapigroup](https://avatars.githubusercontent.com/u/146483151?v=4)](https://github.com/krothapigroup "krothapigroup (1 commits)")[![MrRoundRobin](https://avatars.githubusercontent.com/u/948771?v=4)](https://github.com/MrRoundRobin "MrRoundRobin (1 commits)")[![uncaught](https://avatars.githubusercontent.com/u/10322643?v=4)](https://github.com/uncaught "uncaught (1 commits)")[![10n](https://avatars.githubusercontent.com/u/6480481?v=4)](https://github.com/10n "10n (1 commits)")[![vyskocilpavel](https://avatars.githubusercontent.com/u/28349779?v=4)](https://github.com/vyskocilpavel "vyskocilpavel (1 commits)")[![avenirer](https://avatars.githubusercontent.com/u/3034772?v=4)](https://github.com/avenirer "avenirer (1 commits)")[![Benoit382](https://avatars.githubusercontent.com/u/5646257?v=4)](https://github.com/Benoit382 "Benoit382 (1 commits)")[![bernhardberger](https://avatars.githubusercontent.com/u/2110083?v=4)](https://github.com/bernhardberger "bernhardberger (1 commits)")

---

Tags

clientSSOoauthoauth2microsoftauthorizationazurewindows azureazure active directoryaad

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/jdehais-oauth2-azure/health.svg)

```
[![Health](https://phpackages.com/badges/jdehais-oauth2-azure/health.svg)](https://phpackages.com/packages/jdehais-oauth2-azure)
```

###  Alternatives

[thenetworg/oauth2-azure

Azure Active Directory OAuth 2.0 Client Provider for The PHP League OAuth2-Client

2509.6M48](/packages/thenetworg-oauth2-azure)[stevenmaguire/oauth2-keycloak

Keycloak OAuth 2.0 Client Provider for The PHP League OAuth2-Client

2275.9M27](/packages/stevenmaguire-oauth2-keycloak)[patrickbussmann/oauth2-apple

Sign in with Apple OAuth 2.0 Client Provider for The PHP League OAuth2-Client

1132.5M6](/packages/patrickbussmann-oauth2-apple)[stevenmaguire/oauth2-microsoft

Microsoft OAuth 2.0 Client Provider for The PHP League OAuth2-Client

742.3M12](/packages/stevenmaguire-oauth2-microsoft)[brenoroosevelt/oauth2-govbr

Cliente OAuth2 para Gov.br

2011.0k](/packages/brenoroosevelt-oauth2-govbr)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
