Laravel API Authentication Middleware

Laravel 5.6 has a native API authentication middleware as an alternative to Passport (https://laravel.com/docs/5.6/passport). If you are not running an up-to-date version of PHP on your servers however, you are going to have some difficulties using Password (as I learned the hard way). After doing some digging I ran across an article for versions 5.2 and 5.3 (see link below) which I found still applicable.

Setup:

  1. Create field in users table

    $table->string('api_token', 60)->default(str_random(60));
    

    You will need to run php artisan migrate after you make the change.

  2. Add Guard and Provider in auth.php:

  3. Add Middleware to controllers:

    In your controller construct function add

    $this->middleware( 'auth:token' );
    

There are some security caveats with this method and I would recommend using Passport, but if you need something simple you do have another option.

Further Reading:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.