Laravel 內建Auth + 客製密碼驗證規則(Laravel 11)

Laravel 11 有異動許多地方,RouteServiceProvider、AuthServiceProvider… 都統一在AppServiceProvider中處理

新增一個會員的驗證機制來作為範例

  • config/auth.php
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    'guards' => [
    'web' => [
    'driver' => 'session',
    'provider' => 'users',
    ],
    'member' => [
    'driver' => 'session',
    'provider' => 'members',
    ],
    ],

    'providers' => [
    'users' => [
    'driver' => 'eloquent',
    'model' => env('AUTH_MODEL', App\Models\User::class),
    ],

    'members' => [
    'driver' => 'member',
    'model' => App\Models\Member::class,
    ],
    ],
  • AppServiceProvider.php
    1
    2
    3
    4
    5
    6
    public function boot(): void
    {
    Auth::provider('member', function ($app, array $config) {
    return new MemberUserProvider($app['hash'], $config['model']);
    });
    }

新增一個 MemberUserProvider.php 驗證

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php

namespace App\Providers;

use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class MemberUserProvider extends EloquentUserProvider
{
// 新舊資料為了符合,先以md5密碼驗證,再以新密碼驗證
public function validateCredentials(Authenticatable $user, array $credentials)
{
$plain = $credentials['password'];

if ($user->getAuthPassword() === md5($plain)) {
Log::info('使用舊密碼登入');
return true;
}

if (Hash::check($plain, $user->getAuthPassword())) {
Log::info('使用新密碼登入');
return true;
}
Log::info('密碼錯誤');

return false;
}
}
  • Model\Member.php
    新增 Member 取的密碼 function、繼承的Class要改為 Authenticatable
    1
    2
    3
    4
    5
    6
    7
    8
    9
    use Illuminate\Foundation\Auth\User as Authenticatable;

    class Member extends Authenticatable
    {
    public function getAuthPassword()
    {
    return $this->attributes['password'];
    }
    }