You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Passport实现API多用户(管理员/用户)认证方法问询

Hey there! Let's walk through setting up Laravel Passport to authenticate both your regular users and admins using separate guards. I've done this a few times, so here's a step-by-step breakdown that should work smoothly for you:

1. Fix Your Guard Drivers First

Looking at your current auth.php config, you're using token as the driver for both api and admin guards—but Passport requires the passport driver to function properly. Update that first:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'passport', // Switch to passport driver
        'provider' => 'users',
    ],
    'admin' => [
        'driver' => 'passport', // Switch to passport driver
        'provider' => 'admins',
    ],
],

2. Add Passport's Trait to Both Models

Make sure your User and Admin models both use the HasApiTokens trait from Passport—this is what enables them to generate and manage access tokens:
For App\Models\User:

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    // ... rest of your model code
}

For App\Models\Admin:

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable
{
    use HasApiTokens, Notifiable;

    // ... rest of your model code
}

3. Set Up Multi-Model Token Support (Critical!)

By default, Passport's tokens are tied exclusively to the User model. To make it work with your Admin model, we need to adjust the token table to use polymorphic relationships:

  • First, publish Passport's migrations to customize them:
php artisan vendor:publish --tag=passport-migrations
  • Open the create_oauth_access_tokens_table.php migration file, and modify it to add a user_type field (for polymorphic relations):
Schema::create('oauth_access_tokens', function (Blueprint $table) {
    $table->string('id')->primary();
    $table->unsignedBigInteger('user_id')->nullable();
    $table->string('user_type')->nullable(); // Add this line for polymorphic type
    $table->unsignedBigInteger('client_id');
    $table->string('name')->nullable();
    $table->text('scopes')->nullable();
    $table->boolean('revoked');
    $table->timestamps();
    $table->dateTime('expires_at')->nullable();

    // Add composite index for better query performance
    $table->index(['user_id', 'user_type']);
});
  • Run the migration to apply these changes:
php artisan migrate

Next, create a custom Token model to handle the polymorphic relation:
Create App\Models\Passport\Token.php:

namespace App\Models\Passport;

use Laravel\Passport\Token as PassportToken;

class Token extends PassportToken
{
    // Override the user relation to be polymorphic
    public function user()
    {
        return $this->morphTo();
    }
}

Tell both your User and Admin models to use this custom Token model by adding this method to both:

public function accessTokenModel()
{
    return \App\Models\Passport\Token::class;
}

Finally, update your AuthServiceProvider to use the custom Token model globally:

use App\Models\Passport\Token;
use Laravel\Passport\Passport;

public function boot()
{
    $this->registerPolicies();

    Passport::useTokenModel(Token::class);
    // Optional: If you need to customize clients or auth codes, register their models here too
    // Passport::useClientModel(Client::class);
}

4. Generate Passport Encryption Keys

Run the install command to generate the encryption keys Passport needs to sign tokens:

php artisan passport:install

5. Build Authentication Controllers

Create separate controllers for user and admin login to generate their respective tokens:
For regular users (UserAuthController):

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

class UserAuthController extends Controller
{
    public function login(Request $request)
    {
        $validated = $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if (Auth::guard('api')->attempt($validated)) {
            $user = Auth::guard('api')->user();
            // Generate a token for the user
            $token = $user->createToken('UserAccessToken')->accessToken;

            return response()->json([
                'token' => $token,
                'user' => $user
            ], 200);
        }

        return response()->json(['error' => 'Invalid credentials'], 401);
    }
}

For admins (AdminAuthController):

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

class AdminAuthController extends Controller
{
    public function login(Request $request)
    {
        $validated = $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if (Auth::guard('admin')->attempt($validated)) {
            $admin = Auth::guard('admin')->user();
            // Generate a token for the admin
            $token = $admin->createToken('AdminAccessToken')->accessToken;

            return response()->json([
                'token' => $token,
                'admin' => $admin
            ], 200);
        }

        return response()->json(['error' => 'Invalid credentials'], 401);
    }
}

6. Define Your API Routes

In routes/api.php, set up separate routes for user and admin authentication, plus protected routes using their respective guards:

use App\Http\Controllers\Api\UserAuthController;
use App\Http\Controllers\Api\AdminAuthController;
use App\Http\Controllers\Api\UserController;
use App\Http\Controllers\Api\AdminController;

// Public login routes
Route::post('/login', [UserAuthController::class, 'login']);
Route::post('/admin/login', [AdminAuthController::class, 'login']);

// Protected routes for regular users
Route::middleware('auth:api')->group(function () {
    Route::get('/user/profile', [UserController::class, 'profile']);
    // Add other user-specific routes here
});

// Protected routes for admins
Route::middleware('auth:admin')->group(function () {
    Route::get('/admin/dashboard', [AdminController::class, 'dashboard']);
    // Add other admin-specific routes here
});

7. Test the Authentication

When making requests to protected routes, include the generated token in the Authorization header as a Bearer token:

Authorization: Bearer YOUR_GENERATED_TOKEN

Laravel will automatically use the guard specified in the route middleware to validate the token against the correct model.

That's all! This setup lets you authenticate both users and admins separately using Laravel Passport without conflicts.

内容的提问来源于stack exchange,提问作者Pranav Mandlik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:22:49