laravel 11 区分多模块的token
数据表:用户表(users)、管理员表(admin_user),
- 配置bootstrap/app.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'admin_users',
],
'home' => [
'driver' => 'sanctum',
'provider' => 'users',
],
'admin' => [
'driver' => 'sanctum',
'provider' => 'admin_users',
]
],
'providers' => [
'admin_users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', App\Models\AdminUser::class),
],
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', App\Models\User::class),
],
],
-
创建中间件
-
checkHomeEndToken.php
-
checkAdminEndToken.php
php artisan make:middleware checkHomeEndToken // home路由使用
php artisan make:middleware checkAdminEndToken // admin路由使用
- 实现中间件
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class checkHomeEndToken
{
public function handle(Request $request, Closure $next): Response
{
if ($request->user('home') && $request->user('home')->tokenCan('home-end')) {
return $next($request);
}
return response()->json(['message' => '未登录'], 401);
}
}
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class checkAdminEndToken
{
public function handle(Request $request, Closure $next): Response
{
if ($request->user('admin') && $request->user('admin')->tokenCan('admin-end')) {
return $next($request);
}
return response()->json(['message' => '未登录'], 401);
}
}
- 配置路由
路由配置到web.php,api路由不使用了。我把web的csrf去掉了。用的也是token
<?php
use App\Http\Controllers\admin\AuthController;
use Illuminate\Support\Facades\Route;
use App\Http\Middleware\checkAdminEndToken;
use App\Http\Middleware\checkHomeEndToken;
// 前台路由
Route::prefix('/')->middleware(['auth:sanctum',checkHomeEndToken::class])->group(function () {
// 首页
Route::get('',[\App\Http\Controllers\home\IndexController::class,'index']);
});
// 后台管理路由
Route::prefix('admin')->middleware(['auth:sanctum',checkAdminEndToken::class])->group(function () {
// 登录 不使用auth:sanctum
Route::post('login', [AuthController::class,'login'])->withoutMiddleware(['auth:sanctum',checkAdminEndToken::class]);
// 管理员
Route::resource('admin-user', \App\Http\Controllers\admin\AdminUserController::class)->except(['create', 'edit']);
// 角色
Route::resource('role', \App\Http\Controllers\admin\RoleController::class)->except(['create', 'edit']);
});
- 登录
$token = $request->user()->createToken('admin',['admin-end'])->plainTextToken;
完成