Create authenticated API in Laravel with Passport

Last updated : Jul 04, 2021

Click here to browse our Youtube channel.

In this Vikrama Tech article you will get to how to create authenticated API in Laravel with Passport. Laravel API is the most easy to create and is very efficient. Laravel Passport is a tool offered by Laravel which makes this process fluid and swift.

Laravel Passport: why are we building api only with Passport. Actually there is also a manual method of creating api in Laravel that is by creating tokens for each user and managing them for each user, Under the hood Laravel's Passport utlity also does the same but in an automated and abstracted way. In steps further you will get to know how. So it's upto the programmer that he/she wants to use token basd system or Laravel's Passport utility. For more information on Laravel's Passport, you can browse https://laravel.com/docs/7.x/passport , the Laravel's official documentation.

Let's get started:

  1. Open up a terminal and make sure Laravel and Composer is installed on your system and added into the environment variables.

  2. Type laravel new laravel-api and this command will create a fresh Laravel project on your disk.

  3. Then type in composer require laravel/passport this command will download the official Passport package from Composer Package Manager.

  4. Then open up your freshly created project in any IDE of your choice (Atom/Sublime/VS Code/Notepad).

  5. Head upto .env file open this file, and search for DB_DATABASE and type in your database name to the right side of equals sign.

  6. Then return to terminal and type in command php artisan migrate this command will publish all the database tables including Passport tables to your Mysql database.

  7. Then type php artisan passport:install this command will create the encryption keys needed to generate secure access tokens.

  8. Open app/User.php file and code:

    <?php
    namespace App;
    use Illuminate\Contracts\Auth\MustVerifyEmail;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;
    use Laravel\Passport\HasApiTokens;
    class User extends Authenticatable {
     use Notifiable,HasApiTokens;
     protected $fillable = [
            'name', 'email', 'password',
     ];
     protected $hidden = [
            'password', 'remember_token',
     ];
     protected $casts = [
            'email_verified_at' => 'datetime',
     ];
    }

  9. Open app/Providers/AuthServiceProvider.php file and code:

    <?php
    namespace App\Providers;
    
    use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
    
     
    
    use Illuminate\Support\Facades\Gate;
    
    use Laravel\Passport\Passport;
    
    class AuthServiceProvider extends ServiceProvider
    
    {
    
        protected $policies = [
    
            // 'App\Model' => 'App\Policies\ModelPolicy',
    
        ];
    
        public function boot()
    
        {
    
            $this->registerPolicies();
    
            Passport::routes();
    
        }
    
    }

  10. Then open config/auth.php and find 'guards' => and under this you will get 'api' => and under this change 'driver' to 'passport'.


  11. Then open routes/api.php and code:

    <?php
    use Illuminate\Http\Request;
    
    use Illuminate\Support\Facades\Route;
    
    Route::post('login','AuthController@login');
    
    Route::post('register','AuthController@register');
    
    Route::middleware('auth:api')->post('getuser','AuthController@get_user');
  12. Return to terminal and type php artisan make:controller AuthController this command will create controller file to handle requests such as login and register.


  13. Go to app/Http/Controllers/AuthController.php and code:

    
           <?php
           namespace App\Http\Controllers;
           
           use Illuminate\Http\Request;
           
           use Illuminate\Support\Facades\Auth;
           
           use App\User;
           
           class AuthController extends Controller {
           
               public function register(Request $request){
           
                   $request->validate([
           
                       'name' => 'required|string',
           
                       'email' => 'required|string|email|unique:users',
           
                       'password' => 'required|string|confirmed'
           
                   ]);
           
                   $user = new User([
           
                       'name' => $request->name,
           
                       'email' => $request->email,
           
                       'password' => bcrypt($request->password)
           
                   ]);
           
                   $user->save();
           
                   return response()->json([
           
                       'message' => 'Successfully created user!'
           
                   ], 201);
           
               }
           
               public function login(Request $request){
           
                   $request->validate([
           
                       'email' => 'required|string|email',
           
                       'password' => 'required|string'
           
                   ]);
           
                   $credentials = request(['email', 'password']);
           
                   if(!Auth::attempt($credentials))
           
                       return response()->json([
           
                           'message' => 'Unauthorized'
           
                       ], 401);
           
                   $user = $request->user();
           
                   $tokenResult = $user->createToken('token');
           
                   $token = $tokenResult->token;
           
                   $token->save();
           
                   return response()->json([
           
                       'access_token' => $tokenResult->accessToken,
           
                       'token_type' => 'Bearer'
           
                   ]);
           
               }
           
               public function get_user(Request $request){
           
                   return response()->json($request->user());
           
               }
           
           }
    
    

  14. That's it for coding. Now it's time to test the api.

    • First go to Postman utility and if you do not have it then download it from https://www.postman.com/downloads/ and now open it.


    • Now in the url bar type http://localhost:3000/api/register and in the params write name, email, password and password_confirmation and their respective values.


    • For login type http://localhost:3000/api/login and in params type email and password and their respective values and press return key and you will get your access token.



Sign in for comment. Sign in