I’m building an API for android app which requires 2 types of authentication using Laravel 8. Users Auth and Teachers Auth.
The problem that I have is that tokens which are created for users can be used in teachers api requests while they must not work in teachers routes. if someone copied the token of a user can change the user’s data.
I made some changes to the auth.php : I added this to the guards:
'teacher_api' => [ 'driver' => 'passport', 'provider' => 'teacher', ],
'guards' => [ 'teacher' => [ 'driver' => 'session', 'provider' => 'teachers', ], 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', 'hash' => false, ], 'teacher_api' => [ 'driver' => 'passport', 'provider' => 'teachers', ], ],
The providers array:
'providers' => [ 'teachers' => [ 'driver' => 'eloquent', 'model' => AppTeacher::class, ], 'users' => [ 'driver' => 'eloquent', 'model' => AppUser::class, ], ],
The Api Routes:
Route::prefix('teacher')->group(function () { Route::group(['middleware' => 'auth:teacher_api'], function () { Route::get('teacher_info', 'ApiApiController@teacherInfo'); Route::post('update_teacher_info', 'ApiApiController@updateTeacherInfo'); }); });
What step did I forget to do ?
Advertisement
Answer
In case someone was looking an answer related to my question.
- If you’re using laravel 8.x. Don’t try to install sfelix-martins/passport-multiauth package. The package is deprecated because Laravel Passport has a native implementation since version 9.0.
- Try reading these articles. Each of them perform multi-guards with passport scopes and hope you find the solution that you need as I did.
The Articles:
Laravel 8 Multi Authentication API Tutorial
How to setup Multi-Auth for Laravel APIs | by Toby Okeke | Medium