Introduction
Authentication and security are crucial in today’s application building and management process. In this tutorial, we will learn about Laravel APIs Using Passport validations. Api is known to authenticate a user using a session between requests. With the Laravel framework, authenticated api are simpler using a single Oauth2 package Laravel passport.
Setup a Laravel project
1 2 3 4 | composer create-project --prefer-dist laravel/laravel laravel_passport_api #or laravel new laravel_passport_api |
Install the laravel/passport
package
1 2 3 | composer require laravel/passport |
Next they need to update the .env file and add a connection to the databse and run the migrate to create the necessary tables.
1 2 3 | php artisan migrate |
After running, you can see the following results:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | Migration table created successfully. Migrating: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_000000_create_users_table (6.69 seconds) Migrating: 2014_10_12_100000_create_password_resets_table Migrated: 2014_10_12_100000_create_password_resets_table (2.07 seconds) Migrating: 2016_06_01_000001_create_oauth_auth_codes_table Migrated: 2016_06_01_000001_create_oauth_auth_codes_table (3.06 seconds) Migrating: 2016_06_01_000002_create_oauth_access_tokens_table Migrated: 2016_06_01_000002_create_oauth_access_tokens_table (3.66 seconds) Migrating: 2016_06_01_000003_create_oauth_refresh_tokens_table Migrated: 2016_06_01_000003_create_oauth_refresh_tokens_table (2.88 seconds) Migrating: 2016_06_01_000004_create_oauth_clients_table Migrated: 2016_06_01_000004_create_oauth_clients_table (1.51 seconds) Migrating: 2016_06_01_000005_create_oauth_personal_access_clients_table Migrated: 2016_06_01_000005_create_oauth_personal_access_clients_table (0.38 seconds) Migrating: 2020_11_19_000000_create_failed_jobs_table Migrated: 2020_11_19_000000_create_failed_jobs_table (0.55 seconds) |
Configuring Passport
To implement api authentication we need to use the HasApiTokens
passport provided for the models of the application.
Update App / User.php models
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <?php namespace App; use IlluminateContractsAuthMustVerifyEmail; use IlluminateFoundationAuthUser as Authenticatable; use IlluminateNotificationsNotifiable; use LaravelPassportHasApiTokens; class User extends Authenticatable { use Notifiable, HasApiTokens; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; } |
Next we will call Passport::routes()
in boot()
at the app/Providers/AuthServiceProvider.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?php namespace AppProviders; use IlluminateFoundationSupportProvidersAuthServiceProvider as ServiceProvider; use IlluminateSupportFacadesGate; use LaravelPassportPassport; class AuthServiceProvider extends ServiceProvider { /** * The policy mappings for the application. * * @var array */ protected $policies = [ // 'AppModel' => 'AppPoliciesModelPolicy', ]; /** * Register any authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); Passport::routes(); // } } |
Once setup is complete, the next step is to set the default passport as the API authentication method. We will edit the config/auth.php
file
1 2 3 4 5 6 7 8 9 10 11 12 | 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ], |
Building a Simple API Authentication System using Passport
We now have the passport installed and configured in the project. We need to create a UserController to register and login to the application. Update the routes/api.php
file
1 2 3 | Route::post('login', ' <a class="__cf_email__" href="/cdn-cgi/l/email-protection">[email protected]</a> '); Route::post('register', ' <a class="__cf_email__" href="/cdn-cgi/l/email-protection">[email protected]</a> '); |
Create the controller by running the following command:
1 2 | php artisan make:controller UserController |
The above command will create the UserController.php
file in the App / Http / Controllers. Open it and add the signup and login method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | <?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppUser; use IlluminateSupportFacadesAuth; use CarbonCarbon; class UserController extends Controller { public function signup(Request $request) { $request->validate([ 'name' => 'required', 'email' => 'required|email', 'password' => 'required', 'confirm_password' => 'required|same:password', ]); $data = $request->all(); $data['password'] = bcrypt($data['password']); User::create($data); return response()->json(['message'=> 'user created successfully'],201); } public function login(Request $request) { $request->validate([ 'email' => 'required|string|email', 'password' => 'required|string', 'remember_me' => 'boolean' ]); $credentials = request(['email', 'password']); if(!Auth::attempt($credentials)) return response()->json([ 'message' => 'Authorization failed' ], 401); $user = $request->user(); $tokenResult = $user->createToken('Personal Access Token'); $token = $tokenResult->token; if ($request->remember_me) $token->expires_at = Carbon::now()->addWeeks(1); $token->save(); return response()->json([ 'message' => 'Authorization Granted', 'access_token' => $tokenResult->accessToken, 'token_type' => 'Bearer', 'expires_at' => Carbon::parse( $tokenResult->token->expires_at )->toDateTimeString() ]); } } |
Run the application server by command:
1 2 3 | php artisan serve |
Test result
Register [POST]: 127.0.0.1:8000/api/auth/register Login [POST]: 127.0.0.1:8000/api/auth/login
My post is over here and see you again in the next articles.
References:
https://laravel.com/docs/8.x/passport https://codesource.io/authenticating-laravel-apis-using-passport/