PHPackages                             jorgemudry/laravel-remote-token-auth - 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. jorgemudry/laravel-remote-token-auth

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

jorgemudry/laravel-remote-token-auth
====================================

This package provides a hassle-free way to incorporate authentication in your application by integrating with an external api.

1.0.0(1mo ago)326[1 PRs](https://github.com/jorgemudry/laravel-remote-token-auth/pulls)MITPHPPHP ^8.1

Since Mar 1Pushed 7mo ago1 watchersCompare

[ Source](https://github.com/jorgemudry/laravel-remote-token-auth)[ Packagist](https://packagist.org/packages/jorgemudry/laravel-remote-token-auth)[ Docs](https://github.com/jorgemudry/laravel-remote-token-auth)[ RSS](/packages/jorgemudry-laravel-remote-token-auth/feed)WikiDiscussions master Synced 2w ago

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

Laravel Remote Token Auth
=========================

[](#laravel-remote-token-auth)

[![Build Status](https://camo.githubusercontent.com/c96c3eb82d4b6495ae4da92b8f1c91b31a1b1dec12ed4e23b4a4180b7a86a263/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6a6f7267656d756472792f6c61726176656c2d72656d6f74652d746f6b656e2d617574682f6d61696e2e796d6c3f6c6162656c3d6275696c64)](https://github.com/jorgemudry/laravel-remote-token-auth/actions)[![Total Downloads](https://camo.githubusercontent.com/3bda349f11347d46c0c7bcf9b64c5216610660e6ebf3cce4dc202974c149debe/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6a6f7267656d756472792f6c61726176656c2d72656d6f74652d746f6b656e2d61757468)](https://packagist.org/packages/jorgemudry/laravel-remote-token-auth)[![Latest Stable Version](https://camo.githubusercontent.com/1c9d6b2549914d1ef5c48da5a082df557fe26eba747178346b330d7db6b1fc1b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a6f7267656d756472792f6c61726176656c2d72656d6f74652d746f6b656e2d61757468)](https://packagist.org/packages/jorgemudry/laravel-remote-token-auth)[![License](https://camo.githubusercontent.com/b5d7886111391ea586266146d5d76e392f0ba1dc2c2ac9d5e8a3b2297897d914/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6a6f7267656d756472792f6c61726176656c2d72656d6f74652d746f6b656e2d61757468)](https://packagist.org/packages/jorgemudry/laravel-remote-token-auth)[![Stars](https://camo.githubusercontent.com/9a4d66898aa1c689596dfd0cc05eaf0300b3a8bda5a34cb808a2c2d6f95304ae/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f6a6f7267656d756472792f6c61726176656c2d72656d6f74652d746f6b656e2d61757468)](https://github.com/jorgemudry/laravel-remote-token-auth)

This package provides a hassle-free way to incorporate authentication in your application when token validation happens in an external service.

It registers a stateless auth guard (`rta`) that validates the request's bearer token against an external API and builds the authenticated user from the response, so only valid users gain access to your endpoints.

Every step of the process is replaceable, so you can adapt the package to whatever your validation service looks like.

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

[](#requirements)

- PHP 8.1 or higher
- Laravel 10, 11 or 12

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

[](#installation)

You can install the package via composer:

```
composer require jorgemudry/laravel-remote-token-auth
```

The package will automatically register its service provider.

Set the validation endpoint in your `.env` file:

```
REMOTE_TOKEN_AUTH_ENDPOINT=https://your-auth-service.example/validate
```

Optionally, publish the config file to customize the rest:

```
php artisan vendor:publish --tag=remote-token-auth
```

Usage
-----

[](#usage)

To require authentication for a route, add the auth middleware with the *rta* guard:

```
Route::get('/users', function (Request $request) {
    return $request->user();
})->middleware('auth:rta');
```

On every request the package will:

1. Extract the bearer token from the `Authorization` header.
2. Send it (as a bearer token, in a GET request) to the configured endpoint.
3. Extract the user attributes from the JSON response, using the configured `response.user_path`.
4. Build the authenticated user, using the configured `response.user_class`.

### Error handling

[](#error-handling)

Failures are split into two groups, so clients can tell them apart:

- **401 Unauthorized** — the token is missing, malformed, or the validation service explicitly rejected it (a 400, 401 or 403 response by default; configurable via `http.rejection_statuses`). The response body carries a generic message; internal details are never exposed and are written to the application log instead.
- **503 Service Unavailable** — the validation service is unreachable, timed out, returned a 5xx error, or answered with an unexpected status (404 from a mistyped endpoint, 429 rate limiting, ...). The client's token may still be perfectly valid, so it should retry later instead of discarding it. These failures are always reported to the application log.

Configuration
-------------

[](#configuration)

```
return [
    // Name of the guard registered by the package.
    'guard' => 'rta',

    // Endpoint of the external service that validates the token.
    'endpoint' => env('REMOTE_TOKEN_AUTH_ENDPOINT', ''),

    // Timeouts (in seconds, fractions allowed) for the validation request,
    // and the statuses that mean "token rejected" rather than "service down".
    'http' => [
        'timeout' => env('REMOTE_TOKEN_AUTH_TIMEOUT', 5),
        'connect_timeout' => env('REMOTE_TOKEN_AUTH_CONNECT_TIMEOUT', 2),
        'rejection_statuses' => [400, 401, 403],
    ],

    'response' => [
        // Dot-notation path to the user attributes inside the response.
        'user_path' => '',
        // Class used to represent the authenticated user.
        'user_class' => AuthenticatedUser::class,
    ],

    // Optional cache for successful validations (see below).
    'cache' => [
        'enabled' => env('REMOTE_TOKEN_AUTH_CACHE', false),
        'store' => null,
        'ttl' => 60,
        'prefix' => 'remote-token-auth',
    ],

    // The four steps of the authentication pipeline (see "Advanced Usage").
    'actions' => [
        'token-resolver' => GetTokenFromRequestAction::class,
        'token-validator' => MakeValidationRequestAction::class,
        'attributes-resolver' => GetAttributesFromResponseAction::class,
        'user-maker' => CreateUserFromAttributesAction::class,
    ],
];
```

### Caching validations

[](#caching-validations)

By default every authenticated request triggers one HTTP call to the validation service. If that becomes a problem (latency, rate limits), enable the cache:

```
REMOTE_TOKEN_AUTH_CACHE=true
```

Successful validations are cached (keyed by a SHA-256 hash of the token, in the configured `cache.store`) for `cache.ttl` seconds. A response is only cached after the whole pipeline accepts it (attributes resolved, user built), so failed or malformed validations are never cached. If the cache store itself fails or is misconfigured, the package reports the error and falls back to validating directly against the service — a cache outage never rejects valid tokens.

**Trade-off:** a token revoked in the external service keeps working in your application until the TTL expires. Keep the TTL short.

Advanced Usage
--------------

[](#advanced-usage)

### Replacing a single step of the pipeline

[](#replacing-a-single-step-of-the-pipeline)

Each step is a small class bound to a contract from `JorgeMudry\LaravelRemoteTokenAuth\Contracts`:

Config keyContractDefault behavior`token-resolver``ResolvesToken`Reads the bearer token from the request`token-validator``ValidatesToken`GETs the endpoint with the token, returns the JSON body`attributes-resolver``ResolvesAttributes`Extracts the attributes at `response.user_path``user-maker``CreatesUser`Instantiates `response.user_class` with the attributesTo replace a step, implement the matching contract and point the config key to your class. For example, a validator that POSTs the token instead:

```
