PHPackages                             hfig/oauth2-http-client - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. hfig/oauth2-http-client

ActiveLibrary[HTTP &amp; Networking](/categories/http)

hfig/oauth2-http-client
=======================

An asynchronous, lightweight OAuth 2 decorator for the Symfony HTTP Client.

v4.0.0(7mo ago)06Apache-2.0PHPPHP ^8.0

Since Jul 7Pushed 7mo agoCompare

[ Source](https://github.com/hfig/oauth2-http-client)[ Packagist](https://packagist.org/packages/hfig/oauth2-http-client)[ Docs](https://github.com/hfig/oauth2-http-client)[ RSS](/packages/hfig-oauth2-http-client/feed)WikiDiscussions async Synced 1mo ago

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

OAuth 2 decorator for the Symfony HTTP Client
=============================================

[](#oauth-2-decorator-for-the-symfony-http-client)

This is a decorator for the [Symfony HTTP Client](https://symfony.com/doc/current/http_client.html) that helps you call APIs endpoints protected with OAuth 2. It is a fork of the [library of the same name by BejamineFavre](https://github.com/BenjaminFavre/oauth2-http-client).

Why use this fork?
------------------

[](#why-use-this-fork)

The **original library** inspects the response for `401 Unauthorized` before returning the request object to the caller. This means the library **forces all calls to be synchronous**. This is obviously undesirable in many cases.

**This library** reimplements the same as an **asynchronous decorator**. It does this using the standard `AsynchronousDecoratorTrait` handling capabilities of the `symfony/http-client` library.

See below for conversion steps.

Why use this library?
---------------------

[](#why-use-this-library)

It handles all the authentication protocol with the OAuth 2 server and let you focus solely on making your business API calls.

Designed to be minimalist and lightweight, it has literally no dependency at all, apart the Symfony Contracts of course; and it requires only the PHP JSON extension.

The OAuth 2 is protocol enables clients to authenticate in a wide variety of manners (called Grant Types in the OAuth standard).

This decorator aims to provide a minimal implementation of all standard Grant Types out of the box. Too often however, the OAuth 2 server you will have to authenticate to will not follow strict OAuth 2 standard.

But it's easy to add an additional grant type to handle the specific details/requirements of the target service.

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

[](#installation)

```
composer require hfig/oauth2-http-client

```

Usage
-----

[](#usage)

```
use Symfony\Component\HttpClient\HttpClient;
use Hfig\OAuthHttpClient\OAuthHttpClient;
use Hfig\OAuthHttpClient\GrantType\ClientCredentialsGrantType;

$httpClient = HttpClient::create();

// Here we will use the client credentials grant type but it could be any other grant type
$grantType = new ClientCredentialsGrantType(
    $httpClient,
    'https://github.com/login/oauth/access_token', // The OAuth server token URL
    'the-client-id',
    'the-client-password',
    'scope openid email as required' // optional scopes
);

$httpClient = new OAuthHttpClient($httpClient, $grantType);

// Then use $httpClient to make your API calls:
// $httpClient->request(...);
```

How it works
------------

[](#how-it-works)

Each time you make an HTTP request, the decorator will:

- Fetch an access token from cache or from the OAuth server if none is in cache;
- Modify your request to add the access token (usually in a header);
- Make the API call and return the response;
- Optionally, try again with a new access token if the first API call failed because of token expiration.

Customization
-------------

[](#customization)

Implement any of the following interfaces in order to customize the relevant authentication step, and pass an instance of your class via the relevant Decorator setter.

### GrantTypeInterface

[](#granttypeinterface)

A class in charge of fetching an access token from the OAuth server. The decorator comes with four standard grant types:

- AuthorizationCodeGrantType;
- ClientCredentialsGrantType;
- PasswordGrantType;
- RefreshTokenGrantType.

### TokensCacheInterface

[](#tokenscacheinterface)

A class in charge of storing and fetching tokens from cache. By default, the decorator uses MemoryTokensCache that caches the tokens in memory.

### RequestSignerInterface

[](#requestsignerinterface)

A class in charge of modifying the API request in order to add the access token. By default, the decorator uses BearerHeaderRequestSigner that adds the access token in the Authorization header. You can use the HeaderRequestSigner to add the access token in another header, or you can implement the interface for more customization.

### ResponseCheckerInterface

[](#responsecheckerinterface)

A class in charge of checking if the API call failed because of a token expiration. By default, the decorator uses StatusCode401ResponseChecker that identifies 401 response codes as the signal the access token needs to be renewed. It can lead to false positives (401 response code can be returned for other reasons than token expiration), so you can implement the interface if your OAuth server returns exploitable fine-grained error reasons.

Full Symfony-specific example
-----------------------------

[](#full-symfony-specific-example)

Here is a full example of how to use this library inside a Symfony application.

- with custom Grant Type
- with Redis as a cache layer
- with [scoped](https://symfony.com/doc/current/http_client.html#scoping-client) HTTP Client definition
- with different URLs for the OAuth server and the API

First of all, we need to define 2 HTTP Clients: one for the OAuth server and one for the API.

```
framework:
    http_client:
        scoped_clients:
            sharepoint_oauth.client:
                scope: '%env(resolve:SHAREPOINT_OAUTH_URL)%'
                headers:
                    Accept: 'application/json;odata=verbose'
                # other specific headers or settings if needed
            sharepoint_api.client:
                scope: '%env(resolve:SHAREPOINT_API_URL)%'
                headers:
                    Accept: 'application/json;odata=verbose'
                # other specific headers or settings if needed
```

Second, we need to define a custom Grant Type that will fetch the access token from the OAuth server to connect to SharePoint and will use `sharepoint_oauth.client` defined above.

It differs from a built-in `ClientCredentialsGrantType` on purpose, to show how we can customize the authentication process:

```
