March 12, 2017

10 Easy Step to Setup Laravel Passport as Your API Authentication

Recently I'm working on a project where my role is to provide the back-end API required by a front-end application to access some content. And because recently Laravel comes with Passport (since version 5.3), I thought I could leverage and implement it on this project.

At first, I was only relying on the documentation and also laracasts video to setup Passport. But as I go through, some undocumented steps are missing that I had to google it. Luckily I found a a solution from stackoverflow, and my project is back on schedule. Perhaps some of you experiencing the same problem, as I did, here are 10 easy direct steps you can follow (copy & paste) along without any hassles.

Ready?
Here we go...

  1. Run composer require laravel/passport from your shell (command prompt on Windows).
  2. Open the config/app.php file, and add Laravel\Passport\PassportServiceProvider::class somewhere inside the $providers array
  3. Run php artisan:migrate from your shell.
  4. Still at your shell, run php artisan passport:install.
  5. Open the User model class, it is located at app/User.php, and add use Laravel\Passport\HasApiTokens; somewhere between the namespace and the class declaration, also use this HasApiTokens trait inside the class like so use HasApiTokens, Notifiable;.
  6. Open the app/Providers/AuthServiceProvider.php file, and add use Laravel\Passport\Passport;
    between the namespace and the class declaration, and also add this line Passport::routes(); inside the boot() function.
  7. Open the config/auth.php file and change the API driver from token to passport
  8. If you intend to consume your API from the same Laravel application, simply open the app/Http/Kernel.php file, and add \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class inside the $web array.
  9. Run php artisan passport:client to create an Oauth2 client for your API. From this step, you will get a personal access token.
  10. Use the personal access token you get from step #9 and use it to hit your API.
Note that you request header should contain attributes in these formats (mind the space character before the token):
  •  Authorization : "Bearer <token>"
  • Accept : application/json
That's it. I hope this article can be of any use for anyone who is about to start their backend Laravel project with Passport. If you have any question or not sure of what I meant on any of the above steps, feel free to ask in the comment section below.

Happy coding guys ^_^