Consuming Your Own API In Laravel

There have been so many times that I create a new Laravel application and I start putting routes into my routes\api.php file and try to hit that route and get the dreaded {“error”:”Unauthenticated.”} message.

This message seems so counter-intuitive since Laravel ships with code that makes it seem like it would already be taken care of for you. Like this in resources\assets\js\bootstrap.js:

resources\assets\js\bootstrap.js

This code puts the required CSRF token into the headers of axios to authenticate your request. But this isn’t enough to get up and running. We’ll use Laravel Passport to finish the job.

Side Note: This is the best/fastest way I have figured out. If you have a different/better way to get it setup please let me know!

Passport has a lot of instructions and we’ll only need the first part, and the last part. You can go to the docs and follow the first part (Installation) on your own if you wish, but for ease of use I’m just going to cover the steps quickly here.

First, we’ll pull in the package with composer:

composer require laravel/passport

Then we’ll register the service provider in the providers array of our config/app.php:

Laravel\Passport\PassportServiceProvider::class,

Next we’ll need to migrate our database:

php artisan migrate

Then we need have passport setup encryption keys and whatnot:

php artisan passport:install

Then add the HasApiTokens trait to your App\User model. Change the line use Notifiable; to use HasApiTokens, Notifiable; and make sure to import the class Laravel\Passport\HasApiTokens.

Next, call Passport::routes() in the boot method of your app\Providers\AuthServiceProvider file.

And the last part of setting up Passport is changing the api section of your config/auth.php file to use the passport driver instead of token.

Now we can move onto the last piece. Which is at the bottom of the documentation for Passport.

Add the CreateFreshApiToken middleware to your web middleware group in app\Http\Kernel.php:

\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,

Once you’ve done that, you’re golden!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.