Multi Auth with Laravel 5.4 and Passport

后端 未结 7 2147
猫巷女王i
猫巷女王i 2020-12-31 20:46

I am trying to setup multi auth with Laravel Passport, but it doesn\'t seem to support it. I am using the Password Grant to issue tokens which requires me to pass username/p

7条回答
  •  盖世英雄少女心
    2020-12-31 21:31

    I have done it in Laravel 7 without any custom code as suggested other answers. I have just changed 3 file as follows

    config/auth.php file (My new table name is doctors)

    'guards' => [
       ...
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
            'hash' => false,
        ],
        'api-doctors' => [
            'driver' => 'passport',
            'provider' => 'doctors',
        ],
    ],
    
    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        
        'doctors' => [
            'driver' => 'eloquent',
            'model' => App\Doctor::class,
        ],
    ],
    

    Revise my Doctor model similarly as User model (App/Doctor.php)

    ....
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;
    use Laravel\Passport\HasApiTokens;
    
    class Doctor extends Authenticatable
    {
      use HasApiTokens, Notifiable;
    

    Finally define routes using middleware routes/api.php file as follows

    //normal middleware which exist already
    Route::post('/choose', 'PatientController@appointment')->middleware('auth:api');
    
    //newly created middleware provider (at config/auth.php)
    Route::post('/accept', 'Api\DoctorController@allow')->middleware('auth:api-doctors');
    

    Now when you will create new oauth client you may use artisan passport:client --password --provider this command which prompt you in command line for choosing table before that do not forget to run

    php artisan config:cache
    php artisan cache:clear
    

    Also you can create user manually in oauth_clients table by replacing provider column value users to doctors

    Some hints at reference link https://laravel.com/docs/7.x/passport#customizing-the-user-provider

提交回复
热议问题