This was initially written on wogan.blog, but after two rebrands and the whole Gutenberg fiasco the post completely broke, so I’m dusting it off and re-doing it here.
Laravel 5.6 suggests a simple structure for creating API-driven applications. Your API routes are declared in their own routes/api.php file, and can leverage the auth:api Middleware for security. By default, the system uses the built-in API TokenGuard for that, which requires you to come up with your own system for issuing tokens against users. Passport offers a simpler way that doesn’t require you to use the entire system.
To implement this into an existing Laravel project, there’s only a few edits you need to make:
- Install Passport and disable migrations
$ composer require laravel/passport
Out of the box, Passport sets you up for a full-on OAuth system, which we don’t really need. So to prevent it creating unnecessary tables, add the following to
2. Include the CreateFreshAPIToken Middleware
Add this Middleware to your
web stack, in
'web' => [
This will attach an auth token called
laravel_token as a cookie on all future web requests.
3. Include the HasApiToken trait on your User model
class User extends Authenticatable
use Notifiable, \Laravel\Passport\HasApiTokens;
This trait looks for the
laravel_token cookie and automatically logs you in if it’s detected – as long as you’re using the
passport auth driver.
4. Use the passport driver for API auth.
config/auth.php to set the api driver up:
'guards' => [
'api' => [
'driver' => 'passport'
Future requests to the auth:api guard will now run through the passport driver, and one of the things it does is look for that laravel_token cookie.
5. Generate the keys
Finally, generate a set of public/private encryption keys required by Passport:
$ php artisan passport:keys
Passport will use these within the
passport driver to generate and decode the
laravel_token JWT payloads, then use that to authenticate the User model with the
HasApiToken attached. From this point on, you should be able to use VueJS with your secure APIs out the box.
If you’re using the axios library (provided by default), it will grab any cookies that come through the web request, and re-use them on API requests automatically. Just log your user in as normal, and you should expect the client-side API calls to start working.