如何在Laravel API中实现多认证?含双注册登录场景
Hey there! Let's break down your two Laravel API multi-authentication questions clearly—these are super common scenarios when building apps with distinct user types, so I’ll walk you through each step with practical code examples.
Multi-authentication in Laravel API boils down to setting up separate guards, providers, and token systems for each user type. Here's how to do it:
Step 1: Create separate user models and database tables
First, generate a model and migration for each user type (e.g.,AdminandUser). For example:php artisan make:model Admin -mUpdate the migration file for
admins(add fields likename,email,password) and run the migration:php artisan migrateRepeat this for your other user type if needed.
Step 2: Configure authentication guards and providers
Openconfig/auth.phpand add a new guard and provider for your custom user type. For example, forAdmin:// In the 'guards' array 'admin' => [ 'driver' => 'passport', // Use 'jwt' if you're using JWT instead of Passport 'provider' => 'admins', ], // In the 'providers' array 'admins' => [ 'driver' => 'eloquent', 'model' => App\Models\Admin::class, ],Keep the default
apiguard for regular users if needed.Step 3: Set up token authentication (using Passport as an example)
If you’re using Laravel Passport for API tokens:- Install Passport:
composer require laravel/passport php artisan migrate php artisan passport:install - Add the
HasApiTokenstrait to yourAdminandUsermodels:use Laravel\Passport\HasApiTokens; class Admin extends Model { use HasApiTokens, HasFactory, Notifiable; // ... rest of your model code }
- Install Passport:
Step 4: Create authentication controllers
Build separate controllers for each user type (e.g.,AdminAuthControllerandUserAuthController). Here’s a sample login method forAdminAuthController:public function login(Request $request) { $credentials = $request->validate([ 'email' => 'required|email', 'password' => 'required', ]); if (Auth::guard('admin')->attempt($credentials)) { $admin = Auth::guard('admin')->user(); $token = $admin->createToken('AdminAccessToken')->accessToken; return response()->json(['token' => $token], 200); } return response()->json(['error' => 'Invalid credentials'], 401); }Step 5: Protect routes with the correct guard
Inroutes/api.php, group routes by their respective guard middleware:// Admin-only routes Route::group(['middleware' => 'auth:admin'], function () { Route::get('/admin/dashboard', [AdminController::class, 'dashboard']); }); // Regular user routes Route::group(['middleware' => 'auth:api'], function () { Route::get('/user/profile', [UserController::class, 'profile']); });
This is an extension of the first question—we just need to formalize separate registration and login flows for each user type:
Step 1: Build separate registration logic for each user type
In yourAdminAuthController, add a registration method with type-specific validation:public function register(Request $request) { $validated = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:admins', 'password' => 'required|string|min:8|confirmed', 'role' => 'required|in:super_admin,content_editor', // Admin-specific field ]); $admin = Admin::create([ 'name' => $validated['name'], 'email' => $validated['email'], 'password' => Hash::make($validated['password']), 'role' => $validated['role'], ]); $token = $admin->createToken('AdminRegistrationToken')->accessToken; return response()->json(['admin' => $admin, 'token' => $token], 201); }Repeat this for your
UserAuthControllerwith user-specific fields (e.g.,phone_numberinstead ofrole).Step 2: Define separate authentication routes
Inroutes/api.php, map distinct endpoints for each user type's registration and login:// Admin authentication routes Route::post('/admin/register', [AdminAuthController::class, 'register']); Route::post('/admin/login', [AdminAuthController::class, 'login']); // Regular user authentication routes Route::post('/user/register', [UserAuthController::class, 'register']); Route::post('/user/login', [UserAuthController::class, 'login']);Step 3: Ensure guard consistency across flows
Always use the correct guard when handling authentication for each type:- For admin login/registration:
Auth::guard('admin') - For regular users:
Auth::guard('api')
This ensures Laravel checks the correct database table and model for credentials.
- For admin login/registration:
Step 4: Test the flows thoroughly
Use tools like Postman or curl to test each flow:- Send a POST request to
/api/admin/registerwith admin-specific fields to create an admin user. - Log in with
/api/admin/loginto get a token, then use it to access admin-protected routes. - Repeat the same for regular users to validate their independent flow.
- Send a POST request to
内容的提问来源于stack exchange,提问作者user11410657

