> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Custom UserProviders in Packages

> How to extend where authenticated users are stored from a Laravel package, and safely implement the UserProvider contract, Auth::provider registration, sessions and password rehashing.

When your package retrieves users from somewhere other than Laravel's standard Eloquent model or database, register your own `UserProvider`. For example, you can use an external directory, an existing membership system or a dedicated API as the authentication store.

This is different from creating a new guard. You only supply the implementation that looks up and verifies users for the existing `session` or `token` guards. To change how the guard itself authenticates, see [Custom Authentication Guards](https://kawax.biz/en/advanced/custom-auth-guard.md).

> [!NOTE]
>
> This page targets Laravel 13 and references the `13.x` branch of the official documentation and the implementation in Framework `v13.43.0`. Check the contract methods and password rehashing behavior in every Laravel version your package supports.

## Separate the responsibilities of guards and UserProviders

The guard returned by `Auth::guard()` reads the authentication state from the session or request. When the guard needs a user, it delegates to the configured provider.

```mermaid theme={null}
sequenceDiagram
    participant G as SessionGuard
    participant P as UserProvider
    participant S as External user store
    G->>P: retrieveById / retrieveByCredentials
    P->>S: Look up user
    S-->>P: Stored data
    P-->>G: Authenticatable or null
    G->>P: validateCredentials
    P-->>G: true or false
```

| Extension point | Main responsibility | Where it is configured |
| - | - | - |
| Guard | Manages authentication state from the request, session or token | `auth.guards` |
| UserProvider | Retrieves users, validates passwords and updates remember tokens | `auth.providers` |
| Authenticatable | Exposes the attribute names of the auth identifier, password and remember token | User object |

The value a `UserProvider` returns must be an object that implements `Illuminate\Contracts\Auth\Authenticatable`, not the store's array or an SDK response.

## Register `Auth::provider` from a package

### Register in the service provider's `boot` method

Laravel calls the callback you register with `Auth::provider($name, $callback)` according to the value of `auth.providers.*.driver`. The callback receives the application and the provider configuration.

In your package's service provider, register it before the authentication services are used.

```php theme={null}
<?php

namespace Acme\Directory;

use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\ServiceProvider;

final class DirectoryServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Auth::provider('directory', function (
            Application $app,
            array $config,
        ): UserProvider {
            return new DirectoryUserProvider(
                $app->make(DirectoryClientManager::class)
                    ->connection($config['connection'] ?? 'default'),
                $app->make('hash'),
            );
        });
    }
}
```

`DirectoryClientManager` and `DirectoryUserProvider` are classes your package registers in the container. `$config` comes from the consuming application's `auth.php`, so you can read the connection name, tenant and any other values needed to build the provider from it.

`Auth::provider` registers the name of an authentication **user provider**. It is a separate extension point from the custom guard driver that `Auth::extend` registers. Even when you use both, keep the guard's responsibilities and the user store's responsibilities in separate classes.

### Connect the provider and guard in `auth.php`

Set the registered name as the `driver` in `auth.providers`, and reference that provider from a guard.

```php theme={null}
// config/auth.php
return [
    'defaults' => [
        'guard' => 'directory-web',
        'passwords' => 'users',
    ],

    'guards' => [
        'directory-web' => [
            'driver' => 'session',
            'provider' => 'directory-users',
        ],
    ],

    'providers' => [
        'directory-users' => [
            'driver' => 'directory',
            'connection' => 'primary-directory',
        ],
    ],
];
```

The configuration maps as follows.

1. The `directory-web` guard references the `directory-users` provider.
2. The `driver` of `directory-users` is `directory`, so the callback above is selected.
3. A `SessionGuard` is created and uses the generated `UserProvider` to retrieve users.

`AuthManager` caches a guard the first time it is resolved. There is no API that replaces an already resolved guard after the provider is registered, so pay attention to the boot order of service providers and to using `Auth::forgetGuards()` in tests. If the `auth` configuration is cached, resolve connection details into the configuration and pass them to the callback instead of reading environment variables directly.

## Implement the `UserProvider` contract

In Laravel 13, `Illuminate\Contracts\Auth\UserProvider` requires the following six methods.

```php theme={null}
interface UserProvider
{
    public function retrieveById($identifier);
    public function retrieveByToken($identifier, $token);
    public function updateRememberToken(Authenticatable $user, $token);
    public function retrieveByCredentials(array $credentials);
    public function validateCredentials(Authenticatable $user, array $credentials);
    public function rehashPasswordIfRequired(
        Authenticatable $user,
        array $credentials,
        bool $force = false,
    );
}
```

The three retrieval methods return a user or `null`; a missing user is not represented by an exception. Your package contract decides whether store timeouts and network failures become `null` or a retryable exception. What matters is that you do not hide store failures behind the same "invalid credentials" as an authentication failure.

### Return an `Authenticatable`

This minimal example converts a record from the external store into a `GenericUser` instead of returning it as is. A real package may provide a dedicated user class so that consumers get typed access to extra attributes.

```php theme={null}
use Illuminate\Auth\GenericUser;
use Illuminate\Contracts\Auth\Authenticatable;

private function makeUser(?array $record): ?Authenticatable
{
    if ($record === null) {
        return null;
    }

    // Assumes a record that contains id, password and remember_token.
    return new GenericUser($record);
}
```

`GenericUser` uses the attribute names `id`, `password` and `remember_token` by default. To use other names, override `getAuthIdentifierName()` and related methods in a dedicated class that implements `Authenticatable`.

### Retrieve by ID and remember token

`retrieveById` restores the user from the auth identifier stored in the session. If you support remember-token login, compare the identifier and token against the store.

```php theme={null}
public function retrieveById($identifier): ?Authenticatable
{
    return $this->makeUser($this->client->find($identifier));
}

public function retrieveByToken(
    $identifier,
    #[\SensitiveParameter] $token,
): ?Authenticatable {
    $record = $this->client->find($identifier);
    $rememberToken = $record['remember_token'] ?? null;

    if (! is_string($rememberToken) || ! hash_equals($rememberToken, $token)) {
        return null;
    }

    return $this->makeUser($record);
}

public function updateRememberToken(
    Authenticatable $user,
    #[\SensitiveParameter] $token,
): void {
    $this->client->updateRememberToken(
        $user->getAuthIdentifier(),
        $token,
    );
}
```

Limit the arguments of `hash_equals` to the string retrieved from the store and the token, and never write tokens to logs. If the external store does not support remember tokens, do not leave `updateRememberToken` empty so that it appears to succeed. State clearly in your package's authentication configuration that the remember feature is unavailable.

## Separate credential lookup from password validation

### Do not validate the password in `retrieveByCredentials`

`Auth::attempt()` first looks up the user with `retrieveByCredentials`, then validates the password with `validateCredentials`. If the lookup method also compares passwords, it breaks the processing order the guard expects and password rehashing.

```php theme={null}
use Illuminate\Contracts\Auth\Authenticatable;

public function retrieveByCredentials(
    #[\SensitiveParameter] array $credentials,
): ?Authenticatable {
    $criteria = array_filter(
        $credentials,
        fn (string $key): bool => ! str_contains($key, 'password'),
        ARRAY_FILTER_USE_KEY,
    );

    if ($criteria === []) {
        return null;
    }

    return $this->makeUser($this->client->findBy($criteria));
}
```

Exclude not only `password` but also keys such as `password_confirmation` from the store's lookup criteria. Never include passwords or access tokens in lookup API queries, logs or cache keys. Restricting the accepted lookup keys to an allowlist such as `email` is also an effective way to avoid passing arbitrary fields to an external API.

### Compare hashes in `validateCredentials`

Use the application's `Hasher` for validation, and never send plain-text passwords to the store or write them to logs.

```php theme={null}
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Hashing\Hasher;

public function validateCredentials(
    Authenticatable $user,
    #[\SensitiveParameter] array $credentials,
): bool {
    $plain = $credentials['password'] ?? null;
    $hashed = $user->getAuthPassword();

    if (! is_string($plain) || ! is_string($hashed)) {
        return false;
    }

    return $this->hasher->check($plain, $hashed);
}
```

Return `false` when `$credentials['password']` is missing or the user has no password. If you delegate validation to an external authentication API, keep the same contract and handle failures, timeouts and rate limits according to your package's exception policy.

## Keep password rehashing working

After a successful login, Laravel can check whether the password needs rehashing for the configured hashing algorithm. A custom provider implements `rehashPasswordIfRequired` and updates the hash in the store only when needed.

```php theme={null}
public function rehashPasswordIfRequired(
    Authenticatable $user,
    #[\SensitiveParameter] array $credentials,
    bool $force = false,
): void {
    $plain = $credentials['password'] ?? null;
    $currentHash = $user->getAuthPassword();

    if (! is_string($plain) || ! is_string($currentHash)) {
        return;
    }

    if (! $force && ! $this->hasher->needsRehash($currentHash)) {
        return;
    }

    $this->client->updatePassword(
        $user->getAuthIdentifier(),
        $this->hasher->make($plain),
    );
}
```

Because this writes to the external store, do not ignore rehash failures. If the password attribute of the user object stays stale after the update, the next login may rehash again. Also document, as a package requirement, that the `Hasher` you use matches the password format of the store.

## Test the service provider and the authentication flow

In package tests, swap the store client for a fake and verify each responsibility of the `UserProvider` separately. In particular, check these three points separately.

* `retrieveByCredentials` does not pass the password to the client.
* Only a correct hash passes `validateCredentials`.
* The update API is called only when rehashing is needed.

```php theme={null}
public function test_credentials_lookup_does_not_send_password(): void
{
    $this->client->expects('findBy')
        ->with(['email' => 'user@example.com'])
        ->andReturn([
            'id' => 'user-1',
            'password' => $this->hasher->make('secret'),
            'remember_token' => null,
        ]);

    $user = $this->provider->retrieveByCredentials([
        'email' => 'user@example.com',
        'password' => 'secret',
    ]);

    $this->assertSame('user-1', $user?->getAuthIdentifier());
}
```

Replace `expects` above with the API of the mock library you use. When you use a real HTTP client, check the outgoing request with an HTTP fake and test that the plain-text password never appears in requests or logs.

In integration tests that include the `Auth::provider` registration, use Testbench or similar to verify the following order.

1. Load the package's service provider.
2. Set the custom `driver` in `auth.providers`.
3. Reference that provider from `auth.guards`.
4. Resolve the guard for the first time and confirm that user retrieval is delegated to the fake client.
5. In tests that change configuration or registration, call `Auth::forgetGuards()` before moving on to the next case.

## Design for compatibility across updates

A `UserProvider` sits on the authentication boundary, so check the following when you update your package.

* If you change the attribute names of the `Authenticatable` ID, password or remember token, decide how to handle existing sessions and remember cookies.
* If you change the ID format or password hashing algorithm of the external store, confirm that existing users can still be restored and log in.
* If you narrow the allowed keys of `retrieveByCredentials`, check compatibility with the conditions consumers were passing to `Auth::attempt`.
* Distinguish store failures from authentication failures, and decide on a policy that does not make users re-enter a supposedly wrong password on the login screen.
* Before removing the provider name, the `auth.php` configuration keys or the connection settings, check the configuration cache and your deployment steps.

Treat "which store you return users from, and what you return" and "which hash manages passwords" as part of your package's public contract, and do not leave the handling of credentials entirely to the application.

## Related pages

> [card] [Custom Authentication Guards](https://kawax.biz/en/advanced/custom-auth-guard.md)
>
> Learn how to extend the guard itself and resolve users from sessions or API tokens.

> [card] [Service providers](https://kawax.biz/en/service-providers.md)
>
> Learn the basics of registering your package's service provider and applying extensions at boot.

## Primary sources

* [Laravel official docs: Adding Custom User Providers](https://github.com/laravel/docs/blob/13.x/authentication.md#adding-custom-user-providers)
* [Laravel official docs: User Provider Contract](https://github.com/laravel/docs/blob/13.x/authentication.md#the-user-provider-contract)
* [AuthManager: provider() and guard resolution](https://github.com/laravel/framework/blob/v13.43.0/src/Illuminate/Auth/AuthManager.php)
* [CreatesUserProviders: creating custom providers](https://github.com/laravel/framework/blob/v13.43.0/src/Illuminate/Auth/CreatesUserProviders.php)
* [UserProvider contract](https://github.com/laravel/framework/blob/v13.43.0/src/Illuminate/Contracts/Auth/UserProvider.php)
* [Authenticatable contract](https://github.com/laravel/framework/blob/v13.43.0/src/Illuminate/Contracts/Auth/Authenticatable.php)
* [EloquentUserProvider: default implementation](https://github.com/laravel/framework/blob/v13.43.0/src/Illuminate/Auth/EloquentUserProvider.php)
* [GenericUser: Authenticatable built from attributes](https://github.com/laravel/framework/blob/v13.43.0/src/Illuminate/Auth/GenericUser.php)


## Related topics

- [Advanced Topics](https://kawax.biz/en/advanced/index.md)
- [Custom Authentication Guards](https://kawax.biz/en/advanced/custom-auth-guard.md)
- [Custom session drivers in packages](https://kawax.biz/en/advanced/package-session-drivers.md)
- [Custom providers](https://kawax.biz/en/packages/laravel-copilot-sdk/custom-providers.md)
- [Custom notification channels and delivery testing for packages](https://kawax.biz/en/advanced/package-notification-channels.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.