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

舊的會員資料是使用md5加密,不想再使用md5,且不想讓會員修改密碼,只能在md5雜湊下再使用Hash一次
想要修改 Laravel 的 Auth 驗證方式

新增一個 member 的驗證機制,使用 Hash + md5(password)

設定

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

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

    'members' => [
    'driver' => 'member',
    'model' => App\Models\Member::class,
    ],

新增 MemberUserProvider.php 驗證

  • app/Providers/MemberUserProvider.php
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    namespace App\Providers;  

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


    class MemberUserProvider extends EloquentUserProvider
    {
    public function validateCredentials(Authenticatable $user, array $credentials)
    {
    $plain = $credentials['password'];

    // 客製化驗證
    return Hash::check(md5($plain), $user->getAuthPassword());
    }
    }

新增 Member 取的密碼 function、繼承的Class要改為 Authenticatable

  • app/Models/Member.php
    1
    2
    3
    4
    5
    6
    class Member extends Authenticatable
    {
    public function getAuthPassword()
    {
    return $this->attributes['password'];
    }

Controller 來驗證看看是否可行

1
2
3
4
$credentials = $request->validated();
if (Auth::guard('member')->attempt($credentials)) {
return '登入成功';
}

Token 增加權限

如果有兩個Role,拿對方Role的Token,會導致可以取得相同ID的資料
假設有 admin, member的兩種角色

新增權限的 Middleware

1
2
3
4
5
6
7
8
9
10
11
class MemberRoleAuthMiddleware
{
public function handle(Request $request, Closure $next)
{
if (auth()->user()->tokenCan('auth.member')) {
return $next($request);
}

return response()->json('Not Authorized', 401);
}
}
1
2
3
4
5
6
7
8
9
10
11
class AdminRoleAuthMiddleware
{
public function handle(Request $request, Closure $next)
{
if (auth()->user()->tokenCan('auth.admin')) {
return $next($request);
}

return response()->json('Not Authorized', 401);
}
}

將 Middleware 加入 Http/Kernel.php 中

1
2
3
4
5
protected $routeMiddleware = [
...
'auth.member' => MemberRoleAuthMiddleware::class,
'auth.admin' => AdminRoleAuthMiddleware::class,
];

將 Middleware 加入 Route 中

1
2
3
4
5
6
7
Route::middleware(['auth:sanctum', 'auth.member'])->group(function () {
...
});

Route::middleware(['auth:sanctum', 'auth.admin'])->group(function () {
...
});

參考網站: