1
votes

As I understand it, Passport is used to implement OAuth 2.0 standard support, and as I see it, OAuth 2.0 is an authorization technology and not authentication.

So before authorizing a user to do something, firstly I need to authenticate them. Is there a way for Passport to authenticate a user, or I should use some other means of user authentication? E.g I want to authenticate a user with login and password.

Edit: I'm a little bit confused by the documentation. It's said:

Passport includes an authentication guard that will validate access tokens on incoming requests. Once you have configured the api guard to use the passport driver, you only need to specify the auth:api middleware on any routes that require a valid access token.

So it means that Passport utilizes guards not to authenticate users but to validate access tokens on routes where these tokens are required. Did I get that right?

1

1 Answers

0
votes

Yes, you can use passport tokens for authentication. Make a token for a user and send it as response when a user login. Then apply that authentication to all the routes of that user using laravel guards.(Make sure your model extends Authenticatable and use HasApiTokens) An example for guardians is given below. In auth.php do the following:

   'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'guardians' => [
            'driver' => 'passport',
            'provider' => 'guardians',
            'hash' => false,
        ],
    ],
    
    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
    
        'guardians' => [
            'driver' => 'eloquent',
            'model' => App\Models\Guardian::class,
        ],
    ],

In AuthServiceProvider do this:

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

        //token will expire in one day
        Passport::personalAccessTokensExpireIn(Carbon::now()->addDays(1));
        Passport::routes();
    }

Then in api.php do this to all the routes you want to authenticate.

 Route::group(['middleware' => 'auth:guardians'], function () {
            Route::post('/parent', [ParentController::class, 'parentsList'])
            ->name('parentsList');
        });

Your controller code will be like:

$guardian = Guardian::where('email', $request->email)->first();
if (Hash::check($request->password, $guardian->password)) {
     //passport package implement here...
     $token = $guardian->createToken('Laravel Password Grant Client')->accessToken;

     $data=['guardian'=> $guardian, 'token'=> $token];
     return Response::json($data,200);
 }
 else {
      $data=['error' => 'Mobile Number/Email or Password entered is incorrect.'];
      return Response::json($data, 422);
 }