PHPackages                             pelmered/laravel-http-client-auth-helper - 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. pelmered/laravel-http-client-auth-helper

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

pelmered/laravel-http-client-auth-helper
========================================

v1.1.0(1y ago)265.6k↓26.8%[1 PRs](https://github.com/pelmered/laravel-http-client-auth-helper/pulls)MITPHPPHP ^8.2CI passing

Since Sep 5Pushed 1y ago1 watchersCompare

[ Source](https://github.com/pelmered/laravel-http-client-auth-helper)[ Packagist](https://packagist.org/packages/pelmered/laravel-http-client-auth-helper)[ GitHub Sponsors](https://github.com/pelmered)[ Fund](https://ko-fi.com/pelmered)[ RSS](/packages/pelmered-laravel-http-client-auth-helper/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (6)Dependencies (10)Versions (7)Used By (0)

Laravel HTTP Client Auth helper 🤝
=================================

[](#laravel-http-client-auth-helper-)

An easy-to-use helper for Laravel HTTP Client to make manage API requests with a two-step auth flow. For example, OAuth2 or refresh tokens to get a new short-lived access token.
This helper takes care of all the headaches and boilerplate code with a simple and easy-to-use API.

#### Features:

[](#features)

- Automatically fetches new access tokens when needed.
- Automatically caches the access tokens for their lifetime.
- Extends the Laravel HTTP Client to make it straightforward to use. Se the [usage section](#usage) below for examples.
- Supports common auth flows like OAuth2 and refresh tokens with most grant types.
- No configuration and no boilerplate code required. Just [require](#installation) and use with a simple and consise API.
- Supports [callbacks](#customize-with-callbacks) to customize the behaviour when needed.

#### Vision, roadmap &amp; plans for the future

[](#vision-roadmap--plans-for-the-future)

I want to support as many common auth flows as possible.
If you have a use case that is not super obscure, please [open an issue](https://github.com/pelmered/laravel-http-client-auth-helper/issues/new) where you provide as much detail as possible, or [submit a PR](https://github.com/pelmered/laravel-http-client-auth-helper/pulls) with a working solution.

##### Plans for 1.1 - [Milestone](https://github.com/pelmered/laravel-http-client-auth-helper/milestone/2)

[](#plans-for-11---milestone)

- Helper for automatically refresh tokens in the background before they expire.
- Add support for authorization\_code and implicit OAuth2 grants.
- Tokens owned by a model. For example, tokens associated with a user model rather than the whole application.

[![Latest Stable Version](https://camo.githubusercontent.com/f61b1568dde3370b6dbfdc4f4674865ac1aa5ac35e4a95e5edd56a2a362707e9/68747470733a2f2f706f7365722e707567782e6f72672f70656c6d657265642f6c61726176656c2d687474702d636c69656e742d617574682d68656c7065722f762f737461626c65)](https://packagist.org/packages/pelmered/laravel-http-client-auth-helper)[![Total Downloads](https://camo.githubusercontent.com/7e0247bd6d8e6dd0af6d271b6f51fdad187d35ddd04347f0b3f04803848f3b31/68747470733a2f2f706f7365722e707567782e6f72672f70656c6d657265642f6c61726176656c2d687474702d636c69656e742d617574682d68656c7065722f642f746f74616c)](//packagist.org/packages/pelmered/laravel-http-client-auth-helper)[![Monthly Downloads](https://camo.githubusercontent.com/616299f6fd8ed2a0c52b57d67bd5c5918b29ebb49781fc59902a2024c7105a80/68747470733a2f2f706f7365722e707567782e6f72672f70656c6d657265642f6c61726176656c2d687474702d636c69656e742d617574682d68656c7065722f642f6d6f6e74686c79)](//packagist.org/packages/pelmered/laravel-http-client-auth-helper)[![License](https://camo.githubusercontent.com/575065dc6471c01b9064b981f7e283481dbb6a3f6f63a9000a87a768dbad7b17/68747470733a2f2f706f7365722e707567782e6f72672f70656c6d657265642f6c61726176656c2d687474702d636c69656e742d617574682d68656c7065722f6c6963656e7365)](https://packagist.org/packages/pelmered/laravel-http-client-auth-helper)

[![Tests](https://github.com/pelmered/laravel-http-client-auth-helper/actions/workflows/tests.yml/badge.svg?branch=main)](https://github.com/pelmered/laravel-http-client-auth-helper/actions/workflows/tests.yml)[![Build Status](https://camo.githubusercontent.com/1e865b62a9669b5555f82b90da4fb4b3e744dd64830db6d056decc726927e5d7/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f70656c6d657265642f6c61726176656c2d687474702d636c69656e742d617574682d68656c7065722f6261646765732f6275696c642e706e673f623d6d61696e)](https://scrutinizer-ci.com/g/pelmered/laravel-http-client-auth-helper/build-status/main)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/90c5af21783c38ca86e21c31c43b83694828de73c259df233622d42a9cb365cc/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f70656c6d657265642f6c61726176656c2d687474702d636c69656e742d617574682d68656c7065722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d61696e)](https://scrutinizer-ci.com/g/pelmered/laravel-http-client-auth-helper/?branch=master)[![Code Coverage](https://camo.githubusercontent.com/7f91bbd8e8ce08862a5205814243cd2d71c4bde52c3016b9a3bc3e01903f4ccd/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f70656c6d657265642f6c61726176656c2d687474702d636c69656e742d617574682d68656c7065722f6261646765732f636f7665726167652e706e673f623d6d61696e)](https://scrutinizer-ci.com/g/pelmered/laravel-http-client-auth-helper/?branch=main)

[![Tested on PHP 8.2 to 8.4](https://camo.githubusercontent.com/d45b11711af3df72431b86e8357cbe4cb405b997b729ab887864ed870d52de1b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5465737465642532306f6e2532305048502d382e32253230253743253230382e33253230253743253230382e342d627269676874677265656e2e7376673f6d61784167653d32343139323030)](https://github.com/pelmered/filament-money-field/actions/workflows/tests.yml)[![Tested on OS:es Linux, MacOS, Windows](https://camo.githubusercontent.com/9926c282f083c7a73d0e09f2ebd3b679617d43ce70c34e8fc09029fa10025f74/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5465737465642532306f6e2532306c61737465737425323076657273696f6e732532306f662d2532305562756e74752532302537432532304d61634f5325323025374325323057696e646f77732d627269676874677265656e2e7376673f6d61784167653d32343139323030)](https://github.com/pelmered/laravel-http-client-auth-helper/actions/workflows/tests.yml)

Table of contents
-----------------

[](#table-of-contents)

- [Requirements](#requirements)
- [Vision, roadmap &amp; plans for the future](#vision-roadmap--plans-for-the-future)
- [Contributing](#contributing)
    - [Issues &amp; Bug Reports](#issues--bug-reports)
- [Installation](#installation)
- [Options reference](#options-reference)
    - [scopes - `array`](#scopes---array)
    - [authType - `string`](#authtype---string)
    - [grantType - `string`](#granttype---string)
    - [tokenType - `string`](#tokentype---string)
    - [tokenName - `string`](#tokenname---string)
    - [expires - `int|string|Closure|Carbon`](#expires---intstringclosurecarbon)
    - [accessToken - `string|Closure`](#accesstoken---stringclosure)
    - [tokenTypeCustomCallback - `?Closure`](#tokentypecustomcallback---closure)
    - [cacheKey - `?string`](#cachekey---string)
    - [cacheDriver - `?string`](#cachedriver---string)
- [Usage](#usage)
    - [Minimal example:](#minimal-example)
    - [All parameters with default values:](#all-parameters-with-default-values)
    - [For full type safety, you can also provide objects instead of arrays:](#for-full-type-safety-you-can-also-provide-objects-instead-of-arrays)
    - [Customize with callbacks](#customize-with-callbacks)

    - [Integration tips](#integration-tips)

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- Laravel 10

Vision, roadmap &amp; plans for the future
------------------------------------------

[](#vision-roadmap--plans-for-the-future-1)

I want to support as many common auth flows as possible.
If you have a use case that is not super obscure, please [open an issue](https://github.com/pelmered/laravel-http-client-auth-helper/issues/new) where you provide as much detail as possible, or [submit a PR](https://github.com/pelmered/laravel-http-client-auth-helper/pulls).

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

[](#contributing)

See [Contribution Guide](.github/CONTRIBUTING.md) before sending pull requests.

### Issues &amp; Bug Reports

[](#issues--bug-reports)

When you are submitting issues, I appreciate if you could provide a failing test case. That makes my job a lot easier.
I will try to fix reported issues as soon as possible, but I do this in my spare time, so I might not be able to do it immediately.

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

[](#installation)

```
composer require pelmered/laravel-http-client-auth-helper
```

Usage
-----

[](#usage)

It's really simple to use. Just add the `withRefreshToken` method to your HTTP request and provide the necessary parameters. No configuration needed.

#### Minimal example:

[](#minimal-example)

```
$response = Http::withRefreshToken(
  'https://example.com/token.oauth2',
  [
    'client_id',
    'client_secret',
  ]
)->get(
  'https://example.com/api',
);
```

#### All parameters with default values:

[](#all-parameters-with-default-values)

```
$response = Http::withRefreshToken(
  'https://example.com/token.oauth2',
  [
    'client_id',
    'client_secret',
  ],
  [
    // Options, see the end of the readme for full explaination of each field.
    'scopes' => [],
    'expires' => 'expires_in', // When token should be considered expired. A string key in the response JSON for the expiration. We try to parse different formats and then remove 1 minute to be on the safe side.
    'auth_type' => 'body', // 'body' or 'header'
    'access_token' => 'access_token', // Key for the access token in the response JSON
  ],
  'Bearer'
)->get(
  'https://example.com/api',
);
```

#### For full type safety, you can also provide objects instead of arrays:

[](#for-full-type-safety-you-can-also-provide-objects-instead-of-arrays)

```
use Pelmered\LaravelHttpOAuthHelper\AccessToken;
use Pelmered\LaravelHttpOAuthHelper\Credentials;
use Pelmered\LaravelHttpOAuthHelper\Options;
use Pelmered\LaravelHttpOAuthHelper\RefreshToken;

$response = Http::withRefreshToken(
  'https://example.com/token.oauth2',
  new Credentials(
    clientId: 'client_id',
    clientSecret: 'client_secret',
  ),
  // Options, see the end of the readme for full explaination of each field.
  new Options(
    scopes: ['scope1', 'scope2'],
    expires: 3600,
    grantType: 'password_credentials',
    authType: Credentials::AUTH_TYPE_BODY,
    tokenType: AccessToken::TOKEN_TYPE_BEARER,
  ),
)->get(
  'https://example.com/api',
);
```

#### Customize with callbacks

[](#customize-with-callbacks)

You can also provide callbacks for `expires`, `auth_type`, and `access_token` to customize the behavior.

```
$response = Http::withRefreshToken(
  'https://example.com/token.oauth2',
  [
    'client_id',
    'client_secret',
  ],
  [
    'expires' => fn($response) => $response->json()['expires_in'] - 300, // Should return the ttl in seconds that has been parsed from the response and can be manipulated as you want.
    'access_token' => fn($response) => $response->access_token, // Should return the access token that has been parsed from the response.
  ],
  'Bearer'
)->get(
  'https://example.com/api',
);
```

Custom auth for refreshing token:

```
use Illuminate\Http\Client\PendingRequest;

$response = Http::withRefreshToken(
  'https://example.com/token.oauth2',
  [
    'client_id',
    'client_secret',
  ],
  [
    'expires' => fn($response) => $response->json()['expires_in'] - 300, // Should return the ttl in seconds that has been parsed from the response and can be manipulated as you want.
    'access_token' => fn($response) => $response->access_token, // Should return the access token that has been parsed from the response.
    'auth_type' => 'custom',
    'apply_auth_token' => fn(PendingRequest $httpClient) => $request->withHeader('Authorization', 'Bearer ' . $token),
)->get(
  'https://example.com/api',
);
```

For more examples, check out the [Macro tests](tests/Unit/MacroTest.php).

### Integration tips

[](#integration-tips)

If you use the same token in multiple places, you can create the client only once and save it. For example:

```
$this->client = Http::withRefreshToken(
  'https://example.com/token.oauth2',
  [
    'client_id',
    'client_secret',
  ],
  [
    'scopes' => ['read:posts', 'write:posts', 'read:comments'],
  ]
)->baseUrl('https://example.com/api');
```

to use it later like this:

```
$this->client->get('posts');

$this->client->get('comments');

$this->client->post('posts', [
  'title' => 'My post',
  'content' => 'My content',
]);
```

You can also resolve it in the container if you want. In your service provider:

```
$this->app->singleton('my-oauth-client', function ($app) {
  return Http::withRefreshToken(
    'https://example.com/token.oauth2',
    [
      'client_id',
      'client_secret',
    ],
    [
      'scopes' => ['read:posts', 'write:posts', 'read:comments'],
    ]
  )->baseUrl('https://example.com/api');
});
```

and then use it anywhere like this:

```
app('my-oauth-client')->get('posts');
```

Options reference (Third parameter in `withRefreshToken()`
----------------------------------------------------------

[](#options-reference-third-parameter-in-withrefreshtoken)

### scopes - `array`

[](#scopes---array)

Scopes to send when requesting an access token. Typically only used for OAuth2 flows.
**Possible options:** array with strings **Default:** `[]`

### authType - `string`

[](#authtype---string)

The type of authorization for the refresh token request.
**Possible options:** `Credentials::AUTH_TYPE_BEARER`, `Credentials::AUTH_TYPE_BODY`, `Credentials::AUTH_TYPE_QUERY`, `Credentials::AUTH_TYPE_BASIC`, `Credentials::AUTH_TYPE_CUSTOM`,
**Default:** `Credentials::AUTH_TYPE_BEARER` (=`'Bearer'`)

### grantType - `string`

[](#granttype---string)

Grant type for OAuth2 flows.
**Possible options:** `Credentials::GRANT_TYPE_CLIENT_CREDENTIALS`, `Credentials::GRANT_TYPE_PASSWORD_CREDENTIALS` (authorization\_code and implicit grants are not yet supported. See [issue #3](https://github.com/pelmered/laravel-http-client-auth-helper/issues/3))
**Default:** `Credentials::GRANT_TYPE_CLIENT_CREDENTIALS` (=`'client_credentials'`)

### tokenType - `string`

[](#tokentype---string)

How the access token should be applied to all subsequent requests.
**Possible options:** `AccessToken::TOKEN_TYPE_BEARER`, `AccessToken::TOKEN_TYPE_QUERY`, `AccessToken::TOKEN_TYPE_CUSTOM`
**Default:** `AccessToken::TOKEN_TYPE_BEARER` (=`'Bearer'`)

### tokenName - `string`

[](#tokenname---string)

The name of the token field. This only applies for when the token is applied as a query parameter or to the body of the request.
**Possible options:** Any string
**Default:** `'token'`

### expires - `int|string|Closure|Carbon`

[](#expires---intstringclosurecarbon)

This determines when the access token expires.
**Possible options:**
**integer** - for how long until expiry in seconds)
**string** - Can be key of the field in response that contains the expiry of the token. Can also be a string with a date. This is then parsed by Carbon::parse so any format that Carbon can parse is acceptable.
**Closure** - A closure that receives the refresh response and can return any other acceptable value (integer, string or Carbon object).
**Carbon** - A Carbon object with the time of the expiry.
**Default:** `3600`

### accessToken - `string|Closure`

[](#accesstoken---stringclosure)

This is where the access token can be found on the refresh response.
**Possible options:**
**string** - The key of the access token in the refresh response.
**Closure** - A closure that receives the refresh response and should return the token as a string.
**Default:** `'access_token'`

### tokenTypeCustomCallback - `?Closure`

[](#tokentypecustomcallback---closure)

A callback for giving dull control of how the authentication should be applied. The closure receives the Http client and should return a new Http Client where the auth information has been appended.
**Possible options:**\\ Any closure that returns a Http Client (`Illuminate\Http\Client\PendingRequest`).
**Default:** `null`

### cacheKey - `?string`

[](#cachekey---string)

The cache key that should be used to save the access tokens. If left empty, it will be generated based on the refresh URL.
**Possible options:**
**Default:** `null`

### cacheDriver - `?string`

[](#cachedriver---string)

The cache driver/store that should be used for storing the access tokens. If left empty, the Laravel default will be used.
**Possible options:**
**Default:** `null`

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance48

Moderate activity, may be stable

Popularity32

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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

Every ~46 days

Recently: every ~56 days

Total

6

Last Release

388d ago

Major Versions

v0.2.0 → v1.0.0-beta2024-09-17

PHP version history (2 changes)v0.0.1PHP ^8.1

v0.1.0PHP ^8.2

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/680058?v=4)[Peter Elmered](/maintainers/pelmered)[@pelmered](https://github.com/pelmered)

---

Top Contributors

[![pelmered](https://avatars.githubusercontent.com/u/680058?v=4)](https://github.com/pelmered "pelmered (82 commits)")

---

Tags

hacktoberfesthttp-clientlaravellaravel-package

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/pelmered-laravel-http-client-auth-helper/health.svg)

```
[![Health](https://phpackages.com/badges/pelmered-laravel-http-client-auth-helper/health.svg)](https://phpackages.com/packages/pelmered-laravel-http-client-auth-helper)
```

###  Alternatives

[illuminate/http

The Illuminate Http package.

11936.0M5.1k](/packages/illuminate-http)[api-platform/laravel

API Platform support for Laravel

59126.4k6](/packages/api-platform-laravel)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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