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

# 套件的自訂 UserProvider

> 說明如何從 Laravel 套件擴充驗證使用者的儲存位置，並安全地實作 UserProvider 契約、Auth::provider 註冊、工作階段與密碼重新雜湊。

當套件要從 Laravel 標準的 Eloquent 模型或資料庫以外的地方取得使用者時，請註冊自己的 `UserProvider`。例如可以將外部目錄、既有會員系統或專用 API 作為驗證的儲存位置。

這與新建 Guard 的擴充不同。你只需為既有的 `session` 或 `token` Guard 提供搜尋與驗證使用者的實作。若要變更 Guard 本身的驗證方式，請參閱[自訂驗證 Guard 的實作](https://kawax.biz/zh-TW/advanced/custom-auth-guard.md)。

> [!NOTE]
>
> 本頁以 Laravel 13 為對象，參照官方文件的 `13.x` 分支與 Framework `v13.43.0` 的實作。請在套件支援的每個 Laravel 版本中確認契約的方法與密碼重新雜湊的行為。

## 分離 Guard 與 UserProvider 的職責

`Auth::guard()` 回傳的 Guard 會從工作階段或請求中取出驗證狀態。Guard 取得使用者時，會將處理委派給已設定的提供者。

```mermaid theme={null}
sequenceDiagram
    participant G as SessionGuard
    participant P as UserProvider
    participant S as 外部使用者儲存
    G->>P: retrieveById / retrieveByCredentials
    P->>S: 搜尋使用者
    S-->>P: 儲存的資料
    P-->>G: Authenticatable 或 null
    G->>P: validateCredentials
    P-->>G: true 或 false
```

| 擴充對象 | 主要職責 | 設定位置 |
| - | - | - |
| Guard | 從請求、工作階段、權杖管理驗證狀態 | `auth.guards` |
| UserProvider | 取得使用者、驗證密碼、更新 remember token | `auth.providers` |
| Authenticatable | 公開驗證 ID、密碼與 remember token 的屬性名稱 | 使用者物件 |

`UserProvider` 回傳的值必須是實作 `Illuminate\Contracts\Auth\Authenticatable` 的物件，而不是儲存位置的陣列或 SDK 的回應。

## 從套件註冊 `Auth::provider`

### 在 Service Provider 的 `boot` 中註冊

Laravel 會依 `auth.providers.*.driver` 的值，呼叫透過 `Auth::provider($name, $callback)` 註冊的回呼。回呼會收到應用程式與提供者設定。

在套件的 Service Provider 中，要在驗證服務被使用之前完成註冊。

```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` 與 `DirectoryUserProvider` 是套件註冊到容器中的類別。`$config` 來自使用端應用程式的 `auth.php`，因此可以從中讀取連線名稱、租戶等建立提供者所需的值。

`Auth::provider` 註冊的是驗證**使用者提供者**的名稱。它與 `Auth::extend` 註冊的自訂 Guard 驅動是不同的擴充點。即使兩者都使用，也要將 Guard 的職責與使用者儲存的職責保持在不同的類別中。

### 在 `auth.php` 中連接提供者與 Guard

將註冊的名稱指定為 `auth.providers` 的 `driver`，並從 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',
        ],
    ],
];
```

此設定的對應關係如下。

1. `directory-web` Guard 參照 `directory-users` 提供者。
2. `directory-users` 的 `driver` 為 `directory`，因此會選用前面的回呼。
3. 產生 `SessionGuard`，並使用產生的 `UserProvider` 取得使用者。

`AuthManager` 會在首次解析 Guard 時將其快取。並沒有在註冊提供者後替換已解析 Guard 的 API，因此要留意 Service Provider 的啟動順序，以及在測試中使用 `Auth::forgetGuards()`。若快取了 `auth` 設定，也不要直接從環境變數讀取連線資訊，而應先解析到設定中再傳給回呼。

## 實作 `UserProvider` 契約

Laravel 13 的 `Illuminate\Contracts\Auth\UserProvider` 要求以下 6 個方法。

```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,
    );
}
```

3 個取得類方法會回傳使用者或 `null`，不會以例外表示找不到使用者。儲存位置的逾時或通訊故障要轉換為 `null`，還是作為可重試的例外處理，由套件的契約決定。重要的是不要把驗證失敗與儲存故障都隱藏成相同的「認證資訊不正確」。

### 回傳 `Authenticatable`

以下是不直接回傳外部儲存的紀錄，而是將其轉換為 `GenericUser` 的最小範例。實際的套件也可以提供專用的使用者類別，讓使用者能以型別安全的方式存取額外屬性。

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

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

    // 假設紀錄包含 id、password、remember_token。
    return new GenericUser($record);
}
```

`GenericUser` 預設使用 `id`、`password`、`remember_token` 這些屬性名稱。若要使用其他名稱，請在實作 `Authenticatable` 的專用類別中覆寫 `getAuthIdentifierName()` 等方法。

### 以 ID 與 remember token 取得

`retrieveById` 會從儲存在工作階段中的驗證 ID 還原使用者。若支援透過 remember token 登入，則在儲存位置比對識別碼與權杖。

```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,
    );
}
```

將 `hash_equals` 的引數限定為從儲存位置取得的字串與權杖，並避免將權杖輸出到日誌。若外部儲存不支援 remember token，請不要將 `updateRememberToken` 留空讓它看起來成功，而應在套件的驗證設定中明確說明無法使用 remember 功能。

## 分離認證資訊的搜尋與密碼驗證

### 不要在 `retrieveByCredentials` 中驗證密碼

`Auth::attempt()` 會先以 `retrieveByCredentials` 搜尋使用者，之後再以 `validateCredentials` 驗證密碼。若在搜尋方法中也進行密碼比較，會破壞 Guard 預期的處理順序與密碼重新雜湊。

```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));
}
```

不只 `password`，也要將 `password_confirmation` 等鍵從儲存位置的搜尋條件中排除。請勿將密碼或存取權杖放入搜尋 API 的查詢、日誌或快取鍵中。將可接受的搜尋鍵限制在 `email` 等允許清單內的設計，也能有效避免將任意欄位傳給外部 API。

### 在 `validateCredentials` 中比較雜湊

驗證時使用應用程式的 `Hasher`，不要將明文密碼傳送到儲存位置或輸出到日誌。

```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);
}
```

當 `$credentials['password']` 不存在，或使用者沒有密碼時，回傳 `false`。若將驗證委派給外部驗證 API，在遵守相同契約的同時，依照套件的例外方針處理失敗、逾時與速率限制。

## 維持密碼重新雜湊

登入成功後，Laravel 可以確認是否需要依設定的雜湊方式重新雜湊。自訂提供者需實作 `rehashPasswordIfRequired`，僅在需要時更新儲存位置的雜湊。

```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),
    );
}
```

由於會更新外部儲存，請不要忽略重新雜湊的失敗。若更新後回傳的使用者物件的密碼屬性仍是舊值，下次驗證時可能會重複重新雜湊。也請在套件需求中明確寫出所用 `Hasher` 與儲存位置的密碼格式一致。

## 測試 Service Provider 與驗證流程

在套件的測試中，將儲存用戶端替換為 fake，並分別驗證 `UserProvider` 的各項職責。特別要分開確認以下 3 點。

* `retrieveByCredentials` 不會將密碼傳給用戶端。
* 只有正確的雜湊才能通過 `validateCredentials`。
* 僅在需要重新雜湊時呼叫更新 API。

```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());
}
```

請將上方的 `expects` 換成所用 mock 函式庫的 API。若使用真實的 HTTP 用戶端，請以 HTTP fake 確認傳送內容，並測試明文密碼不會出現在請求或日誌中。

在包含 `Auth::provider` 註冊的整合測試中，以 Testbench 等驗證以下順序。

1. 載入套件的 Service Provider。
2. 在 `auth.providers` 中設定自訂 `driver`。
3. 從 `auth.guards` 參照該提供者。
4. 首次解析 Guard，並確認使用者取得被委派給 fake 用戶端。
5. 在會變更設定或註冊的測試中，進入下一個案例前呼叫 `Auth::forgetGuards()`。

## 設計更新時的相容性

`UserProvider` 位於驗證的邊界，因此更新套件時要確認以下事項。

* 變更 `Authenticatable` 的 ID、密碼、remember token 屬性名稱時，決定既有工作階段與 remember cookie 的處理方式。
* 變更外部儲存的 ID 格式或密碼雜湊方式時，確認舊使用者能否被還原並登入。
* 縮小 `retrieveByCredentials` 的允許鍵時，確認與使用者傳給 `Auth::attempt` 的條件是否相容。
* 將儲存故障與驗證失敗區分開來，並決定不會讓使用者在登入畫面誤以為密碼錯誤而重新輸入的方針。
* 刪除 provider 名稱、`auth.php` 的設定鍵或連線設定之前，確認設定快取與部署程序。

套件應將「從哪個儲存位置回傳什麼作為使用者」與「以哪種雜湊管理密碼」視為公開契約，避免將認證資訊的處理過度交給應用程式。

## 相關頁面

> [card] [自訂驗證 Guard 的實作](https://kawax.biz/zh-TW/advanced/custom-auth-guard.md)
>
> 了解如何擴充 Guard 本身，並從工作階段或 API 權杖解析使用者。

> [card] [Service Provider](https://kawax.biz/zh-TW/service-providers.md)
>
> 了解註冊套件的 Service Provider 並在啟動時套用擴充的基礎。

## 參考的一手資料

* [Laravel 官方文件: Adding Custom User Providers](https://github.com/laravel/docs/blob/13.x/authentication.md#adding-custom-user-providers)
* [Laravel 官方文件: User Provider Contract](https://github.com/laravel/docs/blob/13.x/authentication.md#the-user-provider-contract)
* [AuthManager: provider() 與 Guard 解析](https://github.com/laravel/framework/blob/v13.43.0/src/Illuminate/Auth/AuthManager.php)
* [CreatesUserProviders: 建立自訂提供者](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: 預設實作](https://github.com/laravel/framework/blob/v13.43.0/src/Illuminate/Auth/EloquentUserProvider.php)
* [GenericUser: 由屬性建立的 Authenticatable](https://github.com/laravel/framework/blob/v13.43.0/src/Illuminate/Auth/GenericUser.php)


## Related topics

- [進階主題](https://kawax.biz/zh-TW/advanced/index.md)
- [套件的自訂 Session 驅動](https://kawax.biz/zh-TW/advanced/package-session-drivers.md)
- [套件的自訂快取儲存與契約](https://kawax.biz/zh-TW/advanced/package-cache-drivers.md)
- [套件的自訂通知頻道與傳送驗證](https://kawax.biz/zh-TW/advanced/package-notification-channels.md)
- [自訂驗證 Guard 的實作](https://kawax.biz/zh-TW/advanced/custom-auth-guard.md)


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